Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.

The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters «@».

If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.

def do_repl(s)
	s.gsub(/@[a-z]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def badpattern(s)
	return true if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
	return true if /@@/ =~ s
	return true if /@[a-z]@/ =~ s
	return true if not /@/ =~ s
	return false
end

def test
	s = gets.chomp
	if badpattern(s)
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

#!/usr/bin/env ruby

s = gets.chomp
t = s.split('@', -1)
if t.size > 1 && !t[0].empty? && !t[-1].empty? && t[1..-2].each.map { |x| x.size > 1 }.all?
  result = []
  (t.size - 1).times do |i|
    result << t[i][-1] + '@' + t[i + 1][0..-2]
  end
  result[0] = t[0][0..-2] + result[0]
  result[-1] += t[-1][-1]
  puts result * ','
else
  puts "No solution"
end

emailString = gets.chomp.to_s

resultString = String.new
emailCandidate = String.new
finishCandidate = false;

emailString.each_char {|letter|

  if emailCandidate.length == 0
    if letter == '@'
      resultString = 'No solution'
      break
    else
      emailCandidate += letter
    end
  else
    if letter == '@'
      if finishCandidate
        resultString = 'No solution'
        break
      else
        emailCandidate += letter
        finishCandidate = true;
      end
    else
      if finishCandidate
        emailCandidate += letter
        finishCandidate = false;

        if resultString.length == 0
          resultString += emailCandidate
        else
          resultString += ',' + emailCandidate
        end

        emailCandidate = ''
      else
        emailCandidate += letter
      end
    end
  end
}

if finishCandidate
  resultString = 'No solution'
else
  if resultString.length == 0
    resultString = 'No solution'
  else
    resultString += emailCandidate
  end
end

puts resultString

s = gets.strip
unless s[0] != ?@ && s[-1] != ?@ && s.chars.include?(?@) && !s.chars.each_cons(2).map(&:join).include?("@@")
  s = "No solution"
else
  s = s.split(?@)
  (1...s.size).each do |i|
    if i + 1 == s.size
      s[i - 1] << "@#{s[i]}"
      s.pop
    else
      break s = "No solution" if s[i].size == 1
      s[i - 1] << "@#{s[i][0]}"
      s[i] = s[i][1..-1]
    end
  end
end
puts [*s].join(?,)

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

def nosol
	puts "No solution"
	exit
end

a = gets.gsub("\n", "").split("@", -1)
n = a.size

nosol if a.size < 2 || a[0].empty? || a[-1].empty?
s = a[0]
(1..n - 2).each do |i|
	nosol if a[i].size < 2
	s += "@" + a[i].chr + "," + a[i][1...a[i].size]
end
s += "@" + a[-1]
puts s

s = gets.chomp
arr = s.split("@")
at_count = s.count("@")
ans = ""
if arr.length >= 2 && (arr[1..-2].all?{|e| e.length > 1} && arr[0].length > 0 && arr[-1].length > 0)
	ans << arr[0] + "@"
	at_count -= 1
	arr[1..-2].each do |a|
		ans << "#{a[0]},#{a[1..-1]}@"
		at_count -= 1
	end
	if at_count != 0
		puts "No solution"
	else
		puts ans+arr[-1]
	end
else
	puts "No solution"
end

s = gets
mas = s.chomp!.split("@")

if mas.size < 2 || s[s.length-1..s.length-1] == "@" || s[0..0] == "@" || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length < 2
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

emails = gets.chomp.split("@",-1)
if emails.size < 2 || emails[0].size == 0 || emails[emails.size - 1].size == 0 || (emails.size > 2 &&
  emails[1..emails.size - 2].any? {|x| x.size < 2})
  puts "No solution"
else
  i = 0
  while i + 1 < emails.size
    if i == 0
      print "#{emails[0]}"
    else
      print "#{emails[i][1..emails[i].size]}"
    end
    if i + 2 < emails.size
      print "@#{emails[i+1][0]}"
    else
      print "@#{emails[i+1]}"
    end
    print("#{emails.size > 2 && i + 2 < emails.size ? "," : ""}")
    i += 1
  end
end

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

tokens = line.split("@")

if tokens.length == 1
  puts "No solution"
  exit 0
end

1.upto(tokens.length - 2) do |i|
  if tokens[i].length < 2
    puts "No solution"
    exit 0
  end
end

tokens[0] = "-" + tokens[0]
0.upto(tokens.length - 3) do |i|
  print tokens[i].sub!(/^./, ""), "@", tokens[i+1][0], ","
end

puts "#{tokens[tokens.length-2].sub!(/^./, "")}@#{tokens.last}"

def do_repl(s)
	s.gsub(/@[a-z]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def badpattern(s)
	return true if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
	return true if /@@/ =~ s
	return true if /@[a-z]@/ =~ s
	return true if not /@/ =~ s
	return false
end

def test
	s = gets
	if badpattern(s)
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[^@,]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def test
	s = gets
	if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
		puts "No solution"
		return
	end

	if /@[^@,]@/ =~ s
		puts "No solution"
		return
	end

	if not /@/ =~ s
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[a-z]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def test
	s = gets
	if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
		puts "No solution"
		return
	end

	if /@[a-z]@/ =~ s
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[^@,]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def badpattern(s)
	return true if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
	return true if /@@/ =~ s
	return true if /@[^@,]@/ =~ s
	return true if not /@/ =~ s
	return false
end

def test
	s = gets
	if badpattern(s)
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[^@,]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def test
	s = gets
	if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
		puts "No solution"
		return
	end

	if /@[^@,]@/ =~ s
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[^@]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def test
	s = gets
	if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
		puts "No solution"
		return
	end

	if /@[^@]@/ =~ s
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

def do_repl(s)
	s.gsub(/@[a-z\x80-\xFF]+@/) { |m|
		m.slice(0,2) + "," + m.slice(2, m.length-2)
	}
end

def test
	s = gets
	if s.slice(0,1) == "@" || s.slice(s.length-1,1) == "@"
		puts "No solution"
		return
	end

	if /@[a-z\x80-\xFF]@/ =~ s
		puts "No solution"
		return
	end

	s = do_repl(s)
	s = do_repl(s)
	puts s

end

test

#!/usr/bin/env ruby

t = gets.chomp.split('@')
if t.size > 1 && !t[0].empty? && !t[-1].empty? && t[1..-2].each.map { |x| x.size > 1 }.all?
  result = []
  (t.size - 1).times do |i|
    result << t[i][-1] + '@' + t[i + 1][0..-2]
  end
  result[0] = t[0][0..-2] + result[0]
  result[-1] += t[-1][-1]
  puts result * ','
else
  puts "No solution"
end

emailString = gets.chomp.to_s

resultString = String.new
emailCandidate = String.new
finishCandidate = false;

emailString.each_char {|letter|

  if emailCandidate.length == 0
    if letter == '@'
      resultString = 'No solution'
      break
    else
      emailCandidate += letter
    end
  else
    if letter == '@'
      if finishCandidate
        resultString = 'No solution'
        break
      else
        emailCandidate += letter
        finishCandidate = true;
      end
    else
      if finishCandidate
        emailCandidate += letter
        finishCandidate = false;

        if resultString.length == 0
          resultString += emailCandidate
        else
          resultString += ',' + emailCandidate
        end

        emailCandidate = ''
      else
        emailCandidate += letter
      end
    end
  end
}

if finishCandidate
  resultString = 'No solution'
else
  resultString += emailCandidate
end

puts resultString

s = gets.strip.split(?@)
(1...s.size).each do |i|
  if i + 1 == s.size
    s[i - 1] << "@#{s[i]}"
    s.pop
  else
    break s = "No solution" if s[i].size == 1
    s[i - 1] << "@#{s[i][0]}"
    s[i] = s[i][1..-1]
  end
end
$><<[*s].join(?,)

s = gets.strip
unless s[0] != ?@ && s.chars.include?(?@)
  s = "No solution"
else
  s = s.split(?@)
  (1...s.size).each do |i|
    if i + 1 == s.size
      s[i - 1] << "@#{s[i]}"
      s.pop
    else
      break s = "No solution" if s[i].size == 1
      s[i - 1] << "@#{s[i][0]}"
      s[i] = s[i][1..-1]
    end
  end
end
puts [*s].join(?,)

s = gets.strip
unless s[0] != ?@ && s.chars.include?(?@) && !s.chars.each_cons(2).map(&:join).include?("@@")
  s = "No solution"
else
  s = s.split(?@)
  (1...s.size).each do |i|
    if i + 1 == s.size
      s[i - 1] << "@#{s[i]}"
      s.pop
    else
      break s = "No solution" if s[i].size == 1
      s[i - 1] << "@#{s[i][0]}"
      s[i] = s[i][1..-1]
    end
  end
end
puts [*s].join(?,)

s = gets.strip
if s[0] == ?@
  s = "No solution"
else
  s = s.split(?@)
  (1...s.size).each do |i|
    if i + 1 == s.size
      s[i - 1] << "@#{s[i]}"
      s.pop
    else
      break s = "No solution" if s[i].size == 1
      s[i - 1] << "@#{s[i][0]}"
      s[i] = s[i][1..-1]
    end
  end
end
$><<[*s].join(?,)

def nosol
	puts "No solution"
	exit
end

a = gets.split("@")
n = a.size

s = a[0]
nosol if s.empty? || a[-1].empty?
(1..n - 2).each do |i|
	nosol if a[i].size < 2
	s += "@" + a[i].chr + "," + a[i][1...a.size]
end
s += "@" + a[-1]
puts s

a = gets.split("@")
n = a.size

s = a[0]
(1..n - 2).each do |i|
	if a[i].size < 2
		puts "No solution"
		exit
	end

	s += "@" + a[i].chr + "," + a[i][1...a.size]
end
s += "@" + a[-1]
puts s

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

def nosol
	puts "No solution"
	exit
end

a = gets.gsub("\n", "").split("@")
n = a.size

nosol if a.size < 2 || a[0].empty? || a[-1].empty?
s = a[0]
(1..n - 2).each do |i|
	nosol if a[i].size < 2
	s += "@" + a[i].chr + "," + a[i][1...a[i].size]
end
s += "@" + a[-1]
puts s

def nosol
    puts "No solution"
    exit
end

a = gets.split("@")
n = a.size

s = a[0]
nosol if s.empty? || a[-1].empty?
(1..n - 2).each do |i|
    nosol if a[i].size < 2
    s += "@" + a[i].chr + "," + a[i][1...a[i].size]
end
s += "@" + a[-1]
puts s

arr = gets.chomp.split("@")
ans = ""
if arr.length >= 2 && (arr[1..-2].all?{|e| e.length > 1} && arr[0].length > 0 && arr[-1].length > 0)
	ans << arr[0] + "@"
	arr[1..-2].each do |a|
		ans << "#{a[0]},#{a[1..-1]}@"
	end
	puts ans+arr[-1]
else
	puts "No solution"
end

arr = gets.chomp.split("@")
ans = ""
if arr.length > 2 && (arr[1..-2].all?{|e| e.length > 1} && arr[0].length > 0 && arr[-1].length > 0)
	ans << arr[0] + "@"
	arr[1..-2].each do |a|
		ans << "#{a[0]},#{a[1..-1]}@"
	end
	puts ans+arr[-1]
else
	puts "No solution"
end

mas = gets.split("@")

if mas.size < 2 || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length < 2
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

mas = gets.chomp!.split("@")

if mas.size < 2 || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length < 2
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

mas = gets.chomp!.split("@")

if mas.size < 2 || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length == 1
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

s = gets
mas = s.chomp!.split("@")

if mas.size < 2 || s[mas.length-1..mas.length-1] == "@" || s[0..0] == "@" || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length < 2
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

mas = gets.split("@")
puts mas.size

if mas.size < 2 || mas[0].length == 0 || mas[mas.size-1].length == 0
  puts "No solution"
  exit
end

buffer = mas[0]
for i in 1..mas.size-2
  if mas[i].length < 2
    puts "No solution"
    exit
  end

  buffer += "@"+mas[i][0..(mas[i].length/2)-1]+","+mas[i][(mas[i].length/2)..mas[i].length]
end
buffer += "@"+mas[mas.size-1]

puts buffer

emails = gets.chomp.split("@")
if emails.size < 2 || emails[0].size == 0 || emails[emails.size - 1].size == 0 || (emails.size > 2 &&
  emails[1..emails.size - 2].any? {|x| x.size < 2})
  puts "No solution"
else
  i = 0
  while i + 1 < emails.size
    if i == 0
      print "#{emails[0]}"
    else
      print "#{emails[i][1..emails[i].size]}"
    end
    if i + 2 < emails.size
      print "@#{emails[i+1][0]}"
    else
      print "@#{emails[i+1]}"
    end
    print("#{emails.size > 2 && i + 2 < emails.size ? "," : ""}")
    i += 1
  end
end

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

tokens = line.split("@")

if tokens.length == 1
  puts "No solution"
  exit 0
end

1.upto(tokens.length - 2) do |i|
  if tokens[i].length == 1
    puts "No solution"
    exit 0
  end
end

tokens[0] = "-" + tokens[0]
0.upto(tokens.length - 3) do |i|
  print tokens[i].sub!(/^./, ""), "@", tokens[i+1][0], ","
end

puts "#{tokens[tokens.length-2].sub!(/^./, "")}@#{tokens.last}"

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

tokens = line.split("@")

1.upto(tokens.length - 2) do |i|
  if tokens[i].length == 1
    puts "No solution"
    exit 0
  end
end

print "#{tokens[0]}@#{tokens[1][0]}"
1.upto(tokens.length - 2) do |i|
  1.upto(tokens[i].length - 1) {|j| print tokens[i][j] }
  print "@#{tokens[i+1][0]}"
end

puts tokens.last.sub!(/^./, "")

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

tokens = line.split("@")

1.upto(tokens.length - 2) do |i|
  if tokens[i].length == 1
    puts "No solution"
    exit 0
  end
end

tokens[0] = "-" + tokens[0]
0.upto(tokens.length - 3) do |i|
  print tokens[i].sub!(/^./, ""), "@", tokens[i+1][0], ","
end

puts "#{tokens[tokens.length-2].sub!(/^./, "")}@#{tokens.last}"

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

tokens = line.split("@")

tokens.each do |token|
  if token.length == 1
    puts "No solution"
    exit 0
  end
end

print "#{tokens[0]}@#{tokens[1][0]}"
1.upto(tokens.length - 2) do |i|
  1.upto(tokens[i].length - 1) {|j| print tokens[i][j] }
  print "@#{tokens[i+1][0]}"
end

puts tokens.last.sub!(/^./, "")

#!/usr/bin/ruby

class Solver

end

line = gets.chomp

if line[0] == "@" || line[line.length-1] == "@"
  puts "No solution"
  exit 0
end

ans = true
prev = -1
temp = ""
0.upto(line.length - 1) do |i|
  if line[i] == "@"
    if prev == -1
      prev = i
    else
      if i - prev < 3
        ans = false
        break
      end
    end
  end
  temp += "," if (prev != -1) and (i - prev == 2)
  temp += line[i]
end

if ans
  puts temp
else
  puts "No solution"
end


You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a non-empty string $$$s$$$, consisting only of Latin letters 'a'. The length of $$$s$$$ doesn't exceed $$$50$$$. The second line contains a non-empty string $$$t$$$, consisting of lowercase Latin letters. The length of $$$t$$$ doesn't exceed $$$50$$$.

For each testcase, print the number of different strings $$$s$$$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number.

NoteIn the first example, you can replace any letter 'a' with the string "a", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.In the second example, you can replace the second letter 'a' with "abc". String $$$s$$$ becomes equal to "aabc". Then the second letter 'a' again. String $$$s$$$ becomes equal to "aabcbc". And so on, generating infinitely many different strings.In the third example, you can either leave string $$$s$$$ as is, performing zero moves, or replace the only 'a' with "b". String $$$s$$$ becomes equal to "b", so you can't perform more moves on it.

gets.to_i.times do
  s = gets.chomp
  t = gets.chomp
  answer = if t == "a"
      1
    elsif t.include?("a")
      -1
    else
      2 ** s.size
    end
  p answer
end

gets.to_i.times do
  s = gets.strip.length
  t = gets.strip

  puts(
    if t == 'a'
      1
    elsif t.include?('a')
      -1
    else
      2 ** s
    end
  )
end

T = gets.to_i
T.times do
   s = gets.chomp
   t = gets.chomp

   if t == "a"
       puts 1
       next
   end

   if t.include?(?a) and t.size >= 2
       puts -1
       next
   end

   puts 2**s.size
end

gets.to_i.times do
  s = gets.chomp
  t = gets.chomp
  answer = if t.chars.all? { |c| c == "a" }
      1
    elsif t.include?("a")
      -1
    else
      2 ** s.size
    end
  p answer
end


Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.

The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 1000$$$) — the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the Vova's house description.

Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.

NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$.

n, r = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).each_with_index.to_a
pos, ans = 0, 0
while pos < n
	f = a[[0, pos - r + 1].max...pos + r].reverse_each.find { _1[0] == 1 }
	if f
		ans += 1
		pos = f[1] + r
	else
		puts(-1) + exit
	end
end
puts ans

def result
  n, k = read_ints
  last_idx = n-1
  heaters = read_ints
  heater_idx = [*0...heaters.size].select{ |i| heaters[i] == 1 }

  return -1 if heater_idx.empty?

  lit = 0
  left = 0

  (heater_idx + [nil]).each_cons(2) do |idx, next_idx|

    # can't light back
    return -1 if idx - k + 1 > left

    # next one can light; skip
    next if next_idx && next_idx - k + 1 <= left

    # last one can't light to the end
    return -1 if !next_idx && idx + k - 1 < last_idx

    lit += 1
    left = idx + k

    break if left > last_idx
  end

  lit
end

def solution
  puts result
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def result
  n, k = read_ints
  last_idx = n-1
  heaters = read_ints
  heater_idx = [*0...heaters.size].select{ |i| heaters[i] == 1 }

  return -1 if heater_idx.empty?

  lit = 0
  left = 0

  (heater_idx + [nil]).each_cons(2) do |idx, next_idx|

    # can't light back
    return -1 if idx - k + 1 > left

    # next one can light; skip
    next if next_idx && next_idx - k + 1 <= left

    # last one can't light to the end
    return -1 if !next_idx && idx + k - 1 < last_idx

    lit += 1
    left = idx + k
  end

  lit
end

def solution
  puts result
end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']


You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \le k_i \le n-1$$$) — number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l}$$$ for $$$j \ne l$$$) follow — the chapters required to understand the $$$i$$$-th chapter. It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\cdot10^5$$$.

For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.

NoteIn the first example, we will understand chapters $$$\{2, 4\}$$$ in the first reading and chapters $$$\{1, 3\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\{2, 3, 4\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$.

gets.to_i.times do

n = gets.to_i
@dep = Array.new(n) { k, *a = gets.split.map!(&:to_i); a }.unshift([])

@cache = Array.new(n + 1)
@visited = Array.new(n + 1, false)

=begin
def cnt(k)
  @cache[k] ||= (
    raise if @visited[k]
    @visited[k] = true

    @dep[k].map do |l|
      c = cnt(l)
      k > l ? c : c.succ
    end.max || 1
  )
end
=end

#=begin
def cnt(k)
  return @cache[k] if @cache[k]

  i, j, ret = k, nil, nil
  stack = []

  loop do
    break unless i

    if ret
      ret += 1 if i < @dep[i][j]
      j += 1
      raise StopIteration if @dep[i][j].nil?
      stack << [i, j]
      i, j, ret = @dep[i][j], nil, nil
      next
    end

    if @cache[i]
      ret = @cache[i]
      i, j = stack.pop
      next
    end

    raise if @visited[i]
    @visited[i] = true

    j = 0
    raise StopIteration if @dep[i][j].nil?
    stack << [i, j]
    i, j, ret = @dep[i][j], nil, nil
  rescue StopIteration
    max = @dep[i].map do |jj|
      c = @cache[jj]
      i < jj ? c.succ : c
    end.max || 1
    ret = @cache[i] = max
    i, j = stack.pop
  end

  @cache[k]
end
#=end

begin
  @dep.each_index { |k| cnt(k) }
  puts @cache.max
rescue RuntimeError
  puts -1
end

end

# Priority Queue
# Reference: https://github.com/python/cpython/blob/master/Lib/heapq.py
class PriorityQueue
  # By default, the priority queue returns the maximum element first.
  # If a block is given, the priority between the elements is determined with it.
  # For example, the following block is given, the priority queue returns the minimum element first.
  # `PriorityQueue.new { |x, y| x < y }`
  #
  # A heap is an array for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0.
  def initialize(array = [], &comp)
    @heap = array
    @comp = comp || proc { |x, y| x > y }
    heapify
  end

  attr_reader :heap

  # Push new element to the heap.
  def push(item)
    shift_down(0, @heap.push(item).size - 1)
  end

  alias << push
  alias append push

  # Pop the element with the highest priority.
  def pop
    latest = @heap.pop
    return latest if empty?

    ret_item = heap[0]
    heap[0] = latest
    shift_up(0)
    ret_item
  end

  # Get the element with the highest priority.
  def get
    @heap[0]
  end

  alias top get

  # Returns true if the heap is empty.
  def empty?
    @heap.empty?
  end

  private

  def heapify
    (@heap.size / 2 - 1).downto(0) { |i| shift_up(i) }
  end

  def shift_up(pos)
    end_pos = @heap.size
    start_pos = pos
    new_item = @heap[pos]
    left_child_pos = 2 * pos + 1

    while left_child_pos < end_pos
      right_child_pos = left_child_pos + 1
      if right_child_pos < end_pos && @comp.call(@heap[right_child_pos], @heap[left_child_pos])
        left_child_pos = right_child_pos
      end
      # Move the higher priority child up.
      @heap[pos] = @heap[left_child_pos]
      pos = left_child_pos
      left_child_pos = 2 * pos + 1
    end
    @heap[pos] = new_item
    shift_down(start_pos, pos)
  end

  def shift_down(star_pos, pos)
    new_item = @heap[pos]
    while pos > star_pos
      parent_pos = (pos - 1) >> 1
      parent = @heap[parent_pos]
      break if @comp.call(parent, new_item)

      @heap[pos] = parent
      pos = parent_pos
    end
    @heap[pos] = new_item
  end
end

HeapQueue = PriorityQueue

gets.to_i.times do
  n=gets.to_i
  k=[]
  l=[]
  n.times do
    l << []
  end
  t=[]
  n.times do |i|
    a=gets.split.map(&:to_i)
    k << a[0]
    if a[0]==0
      t << i
    end
    a[1..].each do |aa|
      l[aa-1] << i
    end
  end

  f=true
  ans=1
  e=t.size
  while e<n
#    p t
    pq=PriorityQueue.new(t.dup) {|x,y|x<y}
    t=[]
    while !pq.empty?
      pp=pq.pop
      l[pp].each do |ll|
        k[ll]-=1
        if k[ll]==0
          if ll>pp
            pq.push(ll)
            e+=1
          else
            t << ll
          end
        end
      end
    end
    if e==n
      break
    end
    if t==[]
      f=false
      break
    end
    e+=t.size
    ans+=1
  end
  if f
    puts ans
  else
    puts "-1"
  end
end

gets.to_i.times do

n = gets.to_i
@dep = Array.new(n) { k, *a = gets.split.map!(&:to_i); a }.unshift([])

@cache = Array.new(n + 1)
@visited = Array.new(n + 1, false)

def cnt(k)
  @cache[k] ||= (
    raise if @visited[k]
    @visited[k] = true

    @dep[k].map do |l|
      c = cnt(l)
      k > l ? c : c.succ
    end.min || 1
  )
end

begin
  @dep.each_index { |k| cnt(k) }
  puts @cache.max
rescue RuntimeError
  puts -1
end

end


You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{2n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.

NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution.

n=gets.to_i
a=gets.split.map(&:to_i).sort
if a[0,n].inject(:+)==a[n,n].inject(:+)
    puts "-1"
else
    puts a*' '
end


A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.

Each test consists of 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 an integer $$$n$$$ ($$$3 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 200$$$) — the elements of the array.

Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.

NoteIn the first test case, the subset $$$\{a_2, a_1\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\{a_1, a_3\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset.

def check(n)
  (2..Math.sqrt(n).round).each do |i|
    return true if n % i == 0
  end
  false
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	suma = a.sum
	if check(suma)
		pos = ""
		for i in 1..n do
			pos += i.to_s + " "
		end
		puts n
		puts pos
	else
		pos = ""
		for i in 0..n-1 do
			if(check(suma - a[i]))
				puts n-[i+1,1].min
				for j in 1..n do
					if(i + 1 != j)
						pos += j.to_s + " "
					end
				end
				break
			end
		end
		puts pos
	end
end

def check(x)
	for i in 2..Math.sqrt(x) do
		if x % i == 0
			return true
		end
	end
	return false
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	suma = a.sum
	if check(suma)
		pos = ""
		for i in 1..n do
			pos += i.to_s + " "
		end
		puts n
		puts pos
	else
		pos = ""
		for i in 0..n-1 do
			if(check(suma - a[i]))
				puts n-[i+1,1].min
				for j in 1..n do
					if(i + 1 != j)
						pos += j.to_s + " "
					end
				end
				break
			end
		end
		puts pos
	end
end

def check(x)
	for i in 2..Math.sqrt(x) do
		if x % i == 0
			return true
		end
	end
	return false
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	check = Array.new(20001) {true}
	if check[a.sum]
		savei = 0
		for i in 0..n-1 do
			if !check[a.sum - a[i]]
				savei = i
				break
			end
		end
		puts n-1
		pos = ""
		for i in 0..n do
			if(i != savei)
				pos += (i+1).to_s + " "
			end
		end
		puts pos
	else
		puts n
		pos = ""
		for i in 0..n do
			pos += (i+1).to_s + " "
		end
		puts pos
	end
end

def check(x)
	for i in 2..Math.sqrt(x) do
		if x % i == 0
			return true
		end
	end
	return false
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	if check(a.sum)
		puts n
		po = ""
		for i in 1..n do
			po += i.to_s + " "
		end
		puts po
	else
		puts n-1
		po = ""
		for i in 1..n-1 do
			po += i.to_s + " "
		end
		puts po
	end
end


You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of digits in $$$a$$$. The second line contains a string of $$$n$$$ characters, denoting the number $$$a$$$. Each character is a decimal digit from $$$1$$$ to $$$9$$$. The third line contains exactly $$$9$$$ integers $$$f(1)$$$, $$$f(2)$$$, ..., $$$f(9)$$$ ($$$1 \le f(i) \le 9$$$).

Print the maximum number you can get after applying the operation described in the statement no more than once.

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

pos = (0...n).find { |i| s[i] < a[s[i] - 1] }

if pos
	(pos...n).each do |i|
		break if s[i] > a[s[i] - 1]
		s[i] = a[s[i] - 1]
	end
end
puts s.join

N = gets.to_i
A = gets.chomp
F = gets.chomp.split

f = {}
F.each.with_index(1) do |v, i|
  f[i.to_s] = v
end

indexes = {}

A.chars.each_with_index do |v, i|
  next if indexes[v]

  indexes[v] = i
end

indexes = Hash[indexes.sort_by { |k, v| v }]

ans = A

indexes.each do |d, i|
  if f[d] > d
    list = A.chars
    temp = list.dup
    temp[i..-1].each.with_index(i) do |v, j|
      break if v > f[v]
      list[j] = f[v]
    end

    ans = list.join

    break
  end
end

puts ans

n = gets.to_i
s = gets.chomp.chars.map(&:to_i)
a = gets.split.map(&:to_i)
aaa = (0...n).map { |i| s[i] <= a[s[i] - 1] }.chunk { _1 }.map { [_1, _2.size] }

if aaa[0][0]
	(0...aaa[0][1]).each { |i| s[i] = a[s[i] - 1] }
elsif aaa.size >= 2
	(aaa[0][1]...aaa[1][1]).each { |i| s[i] = a[s[i] - 1] }
end

puts s.join

n = gets.to_i
s = gets.chomp.chars.map(&:to_i)
a = gets.split.map(&:to_i)
(0...n).each { |i| s[i] = [s[i], a[s[i] - 1]].max }
puts s.join

N = gets.to_i
A = gets.to_i
F = gets.split.map(&:to_i)

ans = A

(1..9).each do |d|
  v = A.to_s.gsub(d.to_s, F[d - 1].to_s).to_i
  ans = v if ans < v
end

puts ans

N = gets.to_i
A = gets.to_i
F = gets.split.map(&:to_i)

indexes = {}
A.to_s.each_char.with_index do |ch, i|
  next if indexes[ch]

  indexes[ch.to_i] = i
end

indexes = Hash[indexes.sort_by { |k, v| v }]

ans = A

indexes.each do |d, i|
  if F[d - 1] > d
    ans = A.to_s.gsub(d.to_s, F[d - 1].to_s)
    break
  end
end

puts ans

 N = gets.to_i
A = gets.to_i
F = gets.split.map(&:to_i)

indexes = {}
A.to_s.chars.map(&:to_i).each_with_index do |v, i|
  next if indexes[v]

  indexes[v] = i
end

indexes = Hash[indexes.sort_by { |k, v| v }]

ans = A

indexes.each do |d, i|
  if F[d - 1] > d
    list = A.to_s.chars.map(&:to_i)
    temp = list.dup
    temp[i..-1].each.with_index(i) do |v, j|
      break if v != d
      list[j] = F[d - 1]
    end

    ans = list.join.to_i

    break
  end
end

puts ans


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

n = gets.to_i
sequence = gets.split.map &:to_i

direction_reverse_location = []

sequence.each_index do |i|
  direction_reverse_location << i if sequence[i] - sequence[i - 1]  < 0
end

if direction_reverse_location.length == 0
  puts 0
elsif direction_reverse_location.length > 1
  puts -1
else
  puts (sequence.length - direction_reverse_location.first) % sequence.length
end

#!/usr/bin/env ruby

def decpt(arr)
  res = nil
  (1...arr.size).each do |i|
    if arr[i] < arr[i-1]
      return nil if res
      res = i-1
    end
  end
  res
end

n = gets.to_i
arr = gets.split.map(&:to_i)
if arr.uniq.size == 1
  puts 0
else
  decpt = nil
  arr.size.times do |i|
    if arr[i] < arr[i-1]
      if decpt
        puts -1
        exit
      end
      decpt = i
    end
  end
  if decpt
    puts (arr.size - decpt) % arr.size
  else
    puts 0
  end
end

class B

  def run
    n = $stdin.gets.to_i
    a = $stdin.gets.split(' ').map &:to_i

    i = n - 1
    j = i - 1
    while j >=0 && a[j] <= a[j + 1] do
      j -= 1
    end

    if j == -1
      puts 0
      return
    end

    moves = i - j

    i = j
    j = i - 1
    while j >=0 && a[j] <= a[j + 1] do
      j -= 1
    end

    if j == -1 && a[n-1] <= a[0]
      puts moves
    else
      puts -1
    end
  end

end

B.new.run if __FILE__ == $0

n = gets.to_i
x = gets.split.map &:to_i

ls = x.last
cnt = 0
pos = 0
x.each_with_index do |now, i|
  if now < ls
    cnt += 1
    pos = i
  end
  ls = now
end
puts cnt >= 2 ? -1 : (n - pos) % n

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
c=0
n.times{|i|
	c+=1 if xs[i]>xs[(i+1)%n]
}
if c<2 then
	min1=xs.min
	max1=xs.max
	if min1==max1 then
		puts 0
	else
		ys=(0..(n-1)).map{|i|
			[xs[i],xs[(i+1)%n]]
		}
		puts (n-1)-ys.index([max1,min1])
	end
else
	puts -1
end

def f(n, a)
  bad_i = nil
  bad_c = 0
  n = a.size

  (n-1).times do |i|
    if a[i] > a[i+1]
      bad_c += 1
      bad_i = i
    end
  end

  case bad_c
  when 0; 0
  when 1; a[n-1] <= a[0] ? n - 1 - bad_i : -1
  else -1
  end
end

puts f(STDIN.gets.strip.to_i, STDIN.gets.strip.split.map(&:to_i))

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
prev = arr[0]
ind = nil

(1..(n-1)).each do |i|
	if prev > arr[i]
		ind = i
		break
	end
	prev = arr[i]
end
ans = -1

if ind
	# puts ind
	ans = n - ind if arr[0..(ind-1)] == arr[0..(ind-1)].sort && arr[ind..(n-1)] == arr[ind..(n-1)].sort && arr[-1] <= arr[0]
else
	ans = 0
end

puts ans

n=STDIN.gets.to_i
a=gets.split.map{|x| x.to_i}
i=1
while (i<n)
	if (a[i]<a[i-1])
		break
	end
	i+=1
end
if (i==n)
	puts 0
	exit
end
ans=n-i
i+=1
while (i<n)
	if (a[i]<a[i-1])
		break
	end
	i+=1
end
if (i==n && a[n-1]<=a[0])
	puts ans
else
	puts -1
end

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

before = a.last
reverse_count = 0
reverse_index = 0
a.each_with_index { |v, i|
  if before > v
    reverse_count += 1
    reverse_index = i
  end
  before = v
}

if reverse_count >= 2
  puts -1
else
  puts (n - reverse_index) % n
end

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

newstartindex=0
result=0

for i in 0...n-1 do
    if (arr[i+1]<arr[i])
        result+=1;
        newstartindex=i+1
    end
end

if result==0
    puts 0
    exit
end

if (result==1) && (arr[0]>=arr[n-1])
    puts (n-newstartindex)
    exit
end

puts -1

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

pos = -1
for i in 1...n
  if arr[i - 1] > arr[i]
    pos = i
    break
  end
end

sorted = arr.sort
changed = arr[pos..n] + arr[0..pos-1]

if sorted == arr
  puts 0
elsif sorted == changed
  puts n - pos
else
  puts -1
end

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
p = nil
(n - 1).times { |i|
  if a[i] > a[i + 1]
    if p
      puts -1
      exit
    else
      p = i
    end
  end
}
puts p ? a[-1] <= a[0] ? n - p - 1 : -1 : 0

n = gets.chomp.to_i
seq = gets.chomp.split.map{|i| i.to_i}

ans = 0
(1...n).each do |i|
	if seq[i] < seq[i - 1]
		ans = i
	end
end

sort_seq = seq[(ans...n)] + seq[(0...ans)]

if seq == seq.sort
	puts 0
elsif sort_seq == seq.sort
	puts (n - ans)
else
	puts -1
end

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

n = gets.to_i
tab = gets.split.map(&:to_i)
pivot = 0
(0...tab.size-1).each do |i|
  if tab[i] > tab[i+1]
    pivot = i+1
    break
  end
end

if (tab[0...pivot].sorted? || pivot == 0) &&
  tab[pivot..-1].sorted? &&
    (tab[-1] <= tab[0] || pivot == 0)
  puts (tab.size - pivot) % tab.size
else
  puts -1
end

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}

count = 0
fragmentedIdx = 0

(0...length).each do |idx|
	#puts "idx : #{idx}"
	#puts "sequence[idx % length] #{sequence[idx % length]}"
	#puts "sequence[(idx + 1) % length] #{sequence[(idx + 1) % length]}"
	if sequence[idx % length] > sequence[(idx + 1) % length]
		count += 1
		fragmentedIdx = idx + 1 if count == 1
	end
end

if count > 1
	puts "-1"
	exit
end

if length - fragmentedIdx == length
	puts "0"
else
	puts length - fragmentedIdx
end

#!/usr/bin/env ruby

def sortable?(arr)
  i = arr.index(arr.min)

  prev = arr[i]
  (1...arr.size).each do |k|
    v = arr[(i+k) % arr.size]
    return false if v < prev
    prev = v
  end
  true
end

n = gets.to_i
arr = gets.split.map(&:to_i)
unless sortable?(arr)
  puts -1
else
  idx = arr.index(arr.min)
  puts (arr.size - idx) % arr.size
end

#!/usr/bin/env ruby

def sortable?(arr)
  i = arr.index(arr.min)

  prev = arr[i]
  (1...arr.size).each do |k|
    v = arr[(i+k) % arr.size]
    return false if v != prev+1
    prev = v
  end
  true
end

n = gets.to_i
arr = gets.split.map(&:to_i)
unless sortable?(arr)
  puts -1
else
  idx = arr.index(arr.min)
  puts (arr.size - idx) % arr.size
end

#!/usr/bin/env ruby

def sortable?(arr)
  i = arr.index(arr.min)

  prev = arr[i]
  (1...arr.size).each do |k|
    v = arr[(i+k) % arr.size]
    return false if v < k
    prev = v
  end
  true
end

n = gets.to_i
arr = gets.split.map(&:to_i)
unless sortable?(arr)
  puts -1
else
  idx = arr.index(arr.min)
  puts (arr.size - idx) % arr.size
end

class B

  def run
    n = $stdin.gets.to_i
    a = $stdin.gets.split(' ').map &:to_i

    i = n - 1
    j = i - 1
    while j >=0 && a[j] <= a[i] do
      j -= 1
    end

    if j == -1
      puts 0
      return
    end

    moves = i - j

    i = j
    j = i - 1
    while j >=0 && a[j] <= a[i] do
      j -= 1
    end

    if j == -1 && a[n-1] <= a[0]
      puts moves
    else
      puts -1
    end
  end

end

B.new.run if __FILE__ == $0

class B

  def run
    n = $stdin.gets.to_i
    a = $stdin.gets.split(' ').map &:to_i
    b = a + a

    ans = 2 * n
    start = 0
    while start < n
      i = start + 1
      while b[i] >= b[i-1]
        i += 1
      end
      ans = [ans, start].min if i - start >= n
      start = i
    end

    puts ans == 2 * n ? -1 : ans
  end

end

B.new.run if __FILE__ == $0

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
c=0
n.times{|i|
	c+=1 if xs[i]>xs[(i+1)%n]
}
if c<2 then
	min1=xs.min
	max1=xs.max
	ys=(0..(n-1)).map{|i|
		[xs[i],xs[(i+1)%n]]
	}
	puts (n-1)-ys.index([max1,min1])
else
	puts -1
end

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
c=0
n.times{|i|
	c+=1 if xs[i]>xs[(i+1)%n]
}
if c<2 then
	m=xs.max
	if m==xs[n-1] then
		puts 0
	else
		puts (n-1)-xs.rindex(m)
	end
else
	puts -1
end

n=gets.to_i
arr=Array.new(n)
arr=gets.split(&:to_i)

newstartindex=0
result=0

for i in 0...n-1 do
    if (arr[i+1]<arr[i])
        result+=1;
        newstartindex=i+1
    end
end

if result==0
    puts 0
    exit
end

if (result==1) && arr[0]>=arr[n-1]
    puts (n-newstartindex)
    exit
end

puts -1

# if arr[n-1]>arr[0] && result==0 && n>2
#   puts 0;
#   exit
# end

# if arr[n-1]>arr[0] && n>2
#   result+=1
# end

# if result>1
#   puts -1
#   exit
# end

# puts (n-newstartindex)

n=gets.to_i
arr=Array.new(n)
arr=gets.split(&:to_i)

newstartindex=0
result=0

for i in 0...n-1 do
    if (arr[i+1]<arr[i])
        result+=1;
        newstartindex=i+1
    end
end
if arr[n-1]>arr[0] && result==0 && n>2
    puts 1;
    exit
end

if arr[n-1]>arr[0] && n>2
    result+=1
end

if result>1
    puts -1
    exit
end

if result==0
    puts 0
    exit
end

puts (n-newstartindex)

n=gets.to_i
arr=Array.new(n)
arr=gets.split(&:to_i)

newstartindex=0
result=0

for i in 0...n-1 do
    if (arr[i+1]<arr[i])
        result+=1;
        newstartindex=i+1
    end
end

if arr[n-1]>arr[0] && result==0 && n>2
    puts 0;
    exit
end

if arr[n-1]>arr[0] && n>2
    result+=1
end

if result>1
    puts -1
    exit
end

if result==0
    puts 0
    exit
end

puts (n-newstartindex)

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

pos = -1
for i in 1...n
  if arr[i - 1] > arr[i]
    pos = i
    break
  end
end

sorted = arr.sort
changed = arr[pos..n] + arr[0..pos-1]

if sorted == arr
  puts 0
elsif sorted == changed
  puts pos
else
  puts -1
end

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

n = gets.to_i
tab = gets.split.map(&:to_i)
pivot = tab.index(tab.min)

if (tab[0...pivot].sorted? || pivot == 0) &&
  tab[pivot..-1].sorted? &&
    (tab[-1] <= tab[0] || pivot == 0)
  puts (tab.size - pivot) % tab.size
else
  puts -1
end

n,tab=gets.to_i,gets.split.map(&:to_i)
pivot=tab.index(tab.min)
if pivot == 0 && tab[0..-1].each_cons(2).all? {|a, b| (a <=> b) <= 0}
  puts 0
elsif tab[0...pivot].each_cons(2).all? {|a, b| (a <=> b) <= 0} &&
  tab[pivot...-1].each_cons(2).all? {|a, b| (a <=> b) <= 0} &&
  tab[-1] <= tab[0]
  puts tab.size - pivot
else
  puts -1
end

n,tab=gets.to_i,gets.split.map(&:to_i)
pivot=tab.index(tab.min)
if tab[0...pivot].each_cons(2).all? {|a, b| a <= b} &&
  tab[pivot..-1].each_cons(2).all? {|a, b| a <= b} &&
    (tab[-1] <= tab[0] || pivot == 0)
  puts (tab.size - pivot) % tab.size
else
  puts -1
end

n,tab=gets.to_i,gets.split.map(&:to_i)
pivot=tab.index(tab.min)
if pivot == 0 && tab[0..-1].each_cons(2).all? {|a, b| (a <=> b) <= 0}
  puts 0
elsif tab[0...pivot].each_cons(2).all? {|a, b| (a <=> b) <= 0} &&
  tab[pivot..-1].each_cons(2).all? {|a, b| (a <=> b) <= 0} &&
    tab[-1] <= tab[0]
  puts tab.size - pivot
else
  puts -1
end

n,tab=gets.to_i,gets.split.map(&:to_i)
pivot=tab.index(tab.min)
if pivot == 0 && tab[0..-1].each_cons(2).all? {|a, b| a <= b}
  puts 0
elsif tab[0...pivot].each_cons(2).all? {|a, b| a <= b} &&
  tab[pivot..-1].each_cons(2).all? {|a, b| a <= b} &&
    tab[-1] <= tab[0]
  puts tab.size - pivot
else
  puts -1
end

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

n = gets.to_i
tab = gets.split.map(&:to_i)
pivot = tab.index(tab.min)

if tab[0...pivot].sorted? &&
  tab[pivot..-1].sorted? &&
    (tab[-1] <= tab[0] || pivot == 0)
  puts (tab.size - pivot) % tab.size
else
  puts -1
end

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

count = 0
fragmentedIdx = 0

if (sequence.index(sequence.min) == 0 && sequence.rindex(sequence.max) - sequence.index(sequence.min) != length - 1)
	puts "-1"
	exit
end

(0...(length - 1)).each do |idx|
	if sequence[idx] > sequence[idx + 1]
		#puts "Join"
		count += 1
		fragmentedIdx = idx + 1
	end
end
if count > 1
	puts "-1"
	exit

end

puts length - fragmentedIdx if sequence.index(sequence.min) != 0
puts "0" if sequence.index(sequence.min) == 0

n = gets.chomp.to_i
start = (n / 2) + 1
dNum = 0

(0...n).each do |row|
	if row <= n / 2
		dNum = 2 * (row + 1) - 1
		start -= 1
	else
		dNum = (-2 * row + (2 * n - 1))
		start += 1 if row > n / 2
	end

	(0...n).each do |col|
		if col >= start && dNum > 0
			print 'D'
			dNum -= 1
		else
			print '*'
		end
	end

	puts ''
end

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

#puts "max : #{sequence.rindex(sequence.max)}"
#puts "min : #{sequence.index(sequence.min)}"
if (sequence.index(sequence.min) == 0 && sequence.rindex(sequence.max) - sequence.index(sequence.min) != length - 1) || (sequence.index(sequence.min) != 0 && sequence.index(sequence.min) - sequence.rindex(sequence.max) != 1)
	puts "-1"
	exit
end

sequence.rindex(sequence.max).downto(1).each do |iterNum|
	#puts "iterNum #{iterNum}"

	if sequence[iterNum] < sequence[iterNum - 1]
		puts "-1"
		exit
	end
end

answer = if length - sequence.index(sequence.min) != length
	length - sequence.index(sequence.min)
else
	0
end
puts answer

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

if (sequence.index(sequence.min) == 0 && sequence.index(sequence.max) - sequence.index(sequence.min) != length - 1) && (sequence.index(sequence.min) - sequence.index(sequence.max) != 1)
	puts "-1"
	exit
end

sequence.index(sequence.max).downto(1).each do |iterNum|
	#puts "iterNum #{iterNum}"

	if sequence[iterNum] < sequence[iterNum - 1]
		puts "-1"
		exit
	end
end

answer = if length - sequence.index(sequence.min) != length
	length - sequence.index(sequence.min)
else
	0
end
puts answer

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

if sequence[0] == 99997
puts "max : #{sequence.rindex(sequence.max)}"
puts "min : #{sequence.index(sequence.min)}"
end
if (sequence.index(sequence.min) == 0 && sequence.rindex(sequence.max) - sequence.index(sequence.min) != length - 1)
	puts "-1"
	exit
end

if (sequence.index(sequence.min) != 0 && sequence.index(sequence.min) - sequence.rindex(sequence.max) != 1)
	puts "-1"
	exit
end

sequence.rindex(sequence.max).downto(1).each do |iterNum|
	#puts "iterNum #{iterNum}"

	if sequence[iterNum] < sequence[iterNum - 1]
		puts "-1"
		exit
	end
end

answer = if length - sequence.index(sequence.min) != length
	length - sequence.index(sequence.min)
else
	0
end
puts answer

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

count = 0
fragmentedIdx = 0

if (sequence.index(sequence.min) == 0 && sequence.rindex(sequence.max) - sequence.index(sequence.min) != length - 1)
	puts "-1"
	exit
end

(0...(length - 1)).each do |idx|
	if sequence[idx] > sequence[idx + 1]
		#puts "Join"
		count += 1
		fragmentedIdx = idx + 1
	end
end
puts "-1" if count > 1
puts length - fragmentedIdx if sequence.index(sequence.min) != 0
puts "0" if sequence.index(sequence.min) == 0

length = gets.chomp.to_i
sequence = gets.chomp.split(' ').map {|item| item.to_i}
#sorted = sequence.sort

if (sequence.index(sequence.min) == 0 && sequence.rindex(sequence.max) - sequence.index(sequence.min) != length - 1) && (sequence.index(sequence.min) - sequence.rindex(sequence.max) != 1)
	puts "-1"
	exit
end

sequence.rindex(sequence.max).downto(1).each do |iterNum|
	#puts "iterNum #{iterNum}"

	if sequence[iterNum] < sequence[iterNum - 1]
		puts "-1"
		exit
	end
end

answer = if length - sequence.index(sequence.min) != length
	length - sequence.index(sequence.min)
else
	0
end
puts answer


Let's define the following recurrence: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$Here $$$minDigit(x)$$$ and $$$maxDigit(x)$$$ are the minimal and maximal digits in the decimal representation of $$$x$$$ without leading zeroes. For examples refer to notes.Your task is calculate $$$a_{K}$$$ for given $$$a_{1}$$$ and $$$K$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of independent test cases. Each test case consists of a single line containing two integers $$$a_{1}$$$ and $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$) separated by a space.

For each test case print one integer $$$a_{K}$$$ on a separate line.

1.upto(gets.to_i) do
  a, k = gets.split(' ').map(&:to_i)

  while k>1
    s = a.to_s
    break if s.include? '0'

    a += s.chars.min.to_i * s.chars.max.to_i
    k -= 1
  end

  puts a
end


You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\cdot10^5$$$.

For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.

4

5 3

BBWBW

5 5

BBWBW

5 1

BBWBW

1 1

W

NoteIn the first test case, $$$s$$$="BBWBW" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$="BBBBW". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$="BBWBW" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$="BBBBB". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$="BBWBW" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'.

def solve(str, k)
  count_w = 0
  k.times { |i| count_w += 1 if str[i] == 'W' }
  ans = count_w
  return ans if ans == 0
  (k...str.length).each do |r|
    l = r - k
    count_w -= 1 if str[l] == 'W'
    count_w += 1 if str[r] == 'W'
    ans = count_w if count_w < ans
  end
  ans
end

tests = gets.to_i
tests.times do
  k = gets.split(' ')[1].to_i
  str = gets.chomp
  puts solve(str, k)
end


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

require 'scanf'
EndMark = -1
class Table
    def initialize
        @occurList = {}
        @start = @goal = 1
        @answer = []
    end

    def readInput(n)
        if n == EndMark && !@answer.empty?
            @answer[-1][1]=@goal-1
        end

        if @occurList[n]
            @answer << [@start,@goal]
            nextPos = @goal+1
            @start = @goal = nextPos
            @occurList = {}
        else
            @occurList[n] = true
            @goal += 1
        end
    end

    def printAnswer
        if @answer.empty?
            puts -1
        else
            puts @answer.size
            @answer.each {|a| printPos *a }
        end
    end

    private
    def printPos a,b
        puts "#{a} #{b}"
    end
end

while str = gets
    tool = Table.new

    gets.split(' ').each do |x|
        tool.readInput x
    end

    tool.readInput(EndMark)

    tool.printAnswer
end

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)

h = Hash.new([])

res = []

a.each_with_index do |i, j|
  h[i] += [j + 1]
  if h[i].length() == 2 then
    res << h[i]
    h = Hash.new([])
  end
end

if res.empty? then
  puts -1
else
  puts res.length()
  res.last[1] = n
  tmp = 1
  res.each do |r|
    puts [[r[0], tmp].min, r[1]].join(" ")
    tmp = r[1] + 1
  end
end

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)

h = Hash.new([])

res = []

a.each_with_index do |i, j|
  h[i] += [j + 1]
  if h[i].length() == 2 then
    res << h[i]
    h = Hash.new([])
  end
end

if res.empty? then
  puts -1
else
  puts res.length()
  tmp = res[0][1]
  res.each do |r|
    puts [[r[0], tmp].min, r[1]].join(" ")
    tmp = r[1] + 1
  end
end


A matrix of size $$$n \times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \le i \le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^9$$$) — the elements of the matrix.

For each test output the smallest number of operations required to make the matrix nice.

NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5

T = gets.to_i

T.times do
  n, m = gets.split.map(&:to_i)
  g = n.times.map { gets.split.map(&:to_i) }
  checked = Array.new(n) { Array.new(m, false) }
  ans = 0

  n.times do |y|
    m.times do |x|
      next if checked[y][x]
      checked[y][x] = true

      values = []
      values << g[y][x]

      y2 = y
      x2 = (m - 1) - x
      values << g[y2][x2] if !checked[y2][x2]
      checked[y2][x2] = true

      y3 = (n - 1) - y
      x3 = x
      values << g[y3][x3] if !checked[y3][x3]
      checked[y3][x3] = true

      y4 = (n - 1) - y
      x4 = (m - 1) - x
      values << g[y4][x4] if !checked[y4][x4]
      checked[y4][x4] = true

      ave = values.sort[values.size / 2]
      ans += values.map { |v| (v - ave).abs }.sum
    end
  end

  puts ans
end

I=->{gets.split.map &:to_i}
I[][0].times{n,m=I[]
a=(1..n).map{I[]}
p [a,a.map(&:reverse)].map{|b|[b.reverse,b].map &:flatten}.flatten(1).transpose.map{|q|x,y,z,w=q.sort;w+z-x-y}.sum/4}

T = gets.to_i

T.times do
  n, m = gets.split.map(&:to_i)
  g = n.times.map { gets.split.map(&:to_i) }
  checked = Array.new(n) { Array.new(m, false) }
  ans = 0

  n.times do |y|
    m.times do |x|
      next if checked[y][x]
      checked[y][x] = true

      values = []
      values << g[y][x]

      y2 = y
      x2 = m - x - 1
      values << g[y2][x2] if !checked[y2][x2]
      checked[y2][x2] = true

      y3 = n - y - 1
      x3 = x
      values << g[y3][x3] if !checked[y3][x3]
      checked[y3][x3] = true

      y4 = n - y - 1
      x4 = m - x - 1
      values << g[y4][x4] if !checked[y4][x4]
      checked[y4][x4] = true

      ave = values.sum / values.size
      ans += values.map { |v| (v - ave).abs }.sum
    end
  end

  puts ans
end

T = gets.to_i

T.times do
  n, m = gets.split.map(&:to_i)
  g = n.times.map { gets.split.map(&:to_i) }
  checked = Array.new(n) { Array.new(m, false) }
  ans = 0

  n.times do |y|
    m.times do |x|
      next if checked[y][x]
      checked[y][x] = true

      values = []
      values << g[y][x]

      y2 = y
      x2 = m - x - 1
      values << g[y2][x2] if !checked[y2][x2]
      checked[y2][x2] = true

      y3 = n - y - 1
      x3 = x
      values << g[y3][x3] if !checked[y3][x3]
      checked[y3][x3] = true

      y4 = n - y - 1
      x4 = m - x - 1
      values << g[y4][x4] if !checked[y4][x4]
      checked[y4][x4] = true

      ave = values[values.size / 2]
      ans += values.map { |v| (v - ave).abs }.sum
    end
  end

  puts ans
end


People in the Tomskaya region like magic formulas very much. You can see some of them below.Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:Here, "mod" means the operation of taking the residue after dividing.The expression  means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.

The first line of the input contains the only integer n (1 ≤ n ≤ 106). The next line contains n integers: p1, p2, ..., pn (0 ≤ pi ≤ 2·109).

The only line of output should contain a single integer — the value of Q.

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

=begin
class RQtree

# major method
# :set(ind, value) set array[ind] = value
# :query(i,j) query the minimum number between index i and j
#
	def initialize(array)
		@data = array.clone
		@tree = [0]*1000000
		construct(1, 0,@data.size-1)
	end

	attr_reader :data, :tree
	def min(a,b)
		return a  if a < b
		b
	end

	def construct(ind, i, j)
		if i==j
			@tree[ind] = @data[i]
			return @tree[ind]
		else
			mid = (i+j)/2
			a = construct(2*ind, i, mid)
			b = construct(2*ind+1, mid+1,j)
			@tree[ind] = min(a,b)
			return @tree[ind]
		end
	end

	def inspect(); _inspect(1,0,@data.size-1);end

	def _inspect(ind, b,e)

		puts  "#{b}:#{e} #{@tree[ind]}"
		return if b==e
		_inspect(2*ind, b, (b+e)/2)
		_inspect(2*ind+1, (b+e)/2+1, e)
	end

	def query(i,j); _query(i,j, 1,0, @data.size-1); end

	def _query(i,j,ind, b, e)

		if i>j
			puts 'somethong wrong with index in func _query'
			exit 1
		end

		if i==b and j==e
			return @tree[ind]
		else
			mid = (b+e)/2
			if i>mid
				return _query(i, j, 2*ind+1,  mid+1, e)
			elsif j<= mid
				return _query(i,j,2*ind,b,mid)
			else
				a = _query(i, mid,2*ind,  b, mid)
				b = _query(mid+1,j,2*ind+1, mid+1,e)
				return min(a,b)
			end
		end
	end

	def set(ind, value)
		@data[ind] = value
		update(ind, value)
	end

	def update(ind, value); _update( ind, value,1, 0, @data.size-1);  end

	def _update(ind, value,i,b,e)

		if b==e
			@tree[i] = value
			return
		end
		mid = (b+e)/2
		if ind > mid
			a=_update(ind, value,2*i+1,  mid+1, e)

		else
			_update(ind, value, 2*i, b, mid)
		end
		@tree[i] = min(@tree[2*i], @tree[2*i+1])
	end

end

class Bitree

	def initialize(array)
		@data=array.clone
		@tree= [0]*(array.size+1)
		construct()
	end

	attr_reader :data, :tree
	def construct()
		sum = [0]*(@data.size+1)
		(1..sum.size-1).each do |ind|
			sum[ind] = @data[ind-1]+sum[ind-1]
		end
		@tree[0] = 0
		(1..@tree.size-1).each do |ind|
			i = ind-(ind & -ind)
			@tree[ind] = sum[ind]-sum[i]
		end
	end

	def query(i)
		i+=1
		s=0
		while i>=1
			s+=@tree[i]
			i-= (i&-i)
		end
		s
	end

	def add(i,a)
		@data[i]+=a
		i+=1
		while i<@tree.size
			@tree[i]+=a
			i+=(i&-i)
		end
	end

	def [](i)
		@data[i]
	end
end
=end
=begin
class Graph

	def initialize(g)

		puts 'expected a Array type input' if g.class != Array
		@graph = g
		size = g.size+1
		@visited = [0]*size
		@time = [0] *size
		@father = [-1] *size
		@lev = [-1] * size

	end

	def dfs(); _dfs(-1, [0],0, 1); self;end

	def _dfs(father, time, lev, id)

		@time[id]=time[0]
		@father[id]=father
		@visited[id] = 1
		@lev[id] = lev

		@graph[id].each do |i|
			if @visited[i]!=1
				time[0]+=1
				_dfs(id, time, lev+1 ,i)
			end
		end
	end

	def inspect
		puts "time: #{@time.inspect}"
		puts "father: #{@father.inspect}"
		puts "lev: #{@lev.inspect}"
	end
end

n = gets.to_i
g = [0]*(n+1)

(1..n).each do |i|
	a = gets.split.map(&:to_i)
	g[a[0]] = a[1..(a.size-1)]
end

g = Graph.new(g)

g.dfs.inspect

=end

=begin
n = gets.to_i
m = gets
standing = 0

m.each_char do |c|
	if c == 'X'
		standing += 1
	end
end

if standing == m.size/2
	puts '0'
	puts  m
else

	if standing > m.size/2
		d = standing-m.size/2
		puts d
		(0..m.size-1).each do |i|
			if m[i] == 'X'
				m[i] = 'x'
				d-=1
				break if d==0
			end
		end

		puts m
	else
		d = m.size/2-standing
		puts d
		(0..m.size-1).each do |i|
			if m[i] == 'x'
				m[i] = 'X'
				d-=1
				break if d == 0
			end
		end

		puts m
	end
end
=end

n = gets.to_i

ora = [0] * (n+1)

(1..ora.size-1).each do |ind|
	ora[ind] = ind^ora[ind-1]
end

s = gets.split.map(&:to_i)
ps = 0
s.each do |e|
	ps = ps ^ e
end

s = [0]*(n+1)

(2..n).each do |ind|

	a = n/ind
	b = n%ind
	if a%2==0
		s[ind] = ora[b]
	else
		s[ind] = ora[ind-1]^ora[b]
	end
	ps = ps ^  s[ind]
end
=begin
(2..n).each do |ind|

end
=end
puts ps


One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.

The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.

n,m=gets.split.map(&:to_i)
l,r=1,n
m.times{
	s=gets.split
	i=s[4].to_i
	if s[2]=="left" then
		r=[r,i-1].min
	else
		l=[l,i+1].max
	end
}
puts r<l ? -1 : r-l+1

n,m=gets.split(" ").map(&:to_i)
l=1
r=n
m.times{
    s=gets.split(" ")
    if s[2]=="left"
        r=[r,s[4].to_i-1].min
    else
        l=[l,s[4].to_i+1].max
    end
}
puts r>=l ? r-l+1 : -1

N, M = gets.split.map{|e| e.to_i}

boxes = Array.new(N + 1, true)

M.times do
  words = gets.chomp.split
  direction = words[2]
  pos = words[4].to_i

#  p [direction, pos]

  if (direction == "left")
    pos.upto(N) {|i| boxes[i] = false}
  else
    1.upto(pos) {|i| boxes[i] = false}
  end
end

count = 0
1.upto(N) {|i|
  count += 1 if boxes[i]
}

if (count == 0)
  puts -1
else
  puts count
end

n, m = gets.split(' ').map{|s| s.to_i}
l, u = 1, n
m.times do
  d, i = gets.scan(/(right|left) of (\d+)/u).last
  i = i.to_i
  case d
  when 'right' then l = [l, i+1].max
  when 'left'  then u = [u, i-1].min
  end
end

a = (l..u).to_a
puts a.empty? ? -1 : a.size

n,m=gets.split(" ").map(&:to_i)
l,p=1,n
m.times{
    ls=gets.split(" ")
    if (ls[2]!="left")
        l=[l,(ls[4]).to_i+1].max
    else
        p=[p,(ls[4]).to_i-1].min
    end
}
puts l<=p ? p-l+1 : -1

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

mn = 1
mx = n
m.times do
  l = $stdin.gets
  idx = l.split[-1].to_i
  if l.match(/left/)
    mx = [idx-1, mx].min
  else
    mn = [idx+1, mn].max
  end
end

result = mx-mn+1
p (result > 0) ? result : -1

n, m = gets.chomp.split.map(&:to_i)
a, b = [0, n + 1]
(1..m).each {
  hint = gets.chomp.split
  if hint[2] == 'right'
    a = [hint[4].to_i, a].max
  else
    b = [hint[4].to_i, b].min
  end
}
c = b - a - 1
puts c < 1 ? -1 : c

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

mn = 1
mx = n
m.times do
  l = $stdin.gets
  idx = l.split[-1].to_i
  if l.match(/left/)
    mx = [idx-1, mx].min
  else
    mn = [idx+1, mx].max
  end
end

result = mx-mn+1
p (result > 0) ? result : -1

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

mn = 1
mx = n
m.times do
  l = $stdin.gets
  idx = l.split[-1].to_i
  if l.match(/left/)
    mx = [idx-1, mx].min
  else
    mn = [idx+1, mn].max
  end
end

p [mn, mx]
result = mx-mn+1
p (result > 0) ? result : -1


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:

N = gets.to_i
ns = Array.new(N+1,0)
(N-1).times {
  a,b = gets.split.map &:to_i
  ns[a] += 1
  ns[b] += 1
}
puts ns.count(2) == 0 ? "YES" : "NO"

n = gets.to_i
deg = [0]*(n)
(n-1).times do
  u,v = gets.split.map(&:to_i)
  deg[u-1] += 1
  deg[v-1] += 1
end
puts deg.include?(2) ? "NO" : "YES"

N = gets.to_i
ns = Array.new(N+1,0)
(N-1).times {
  a,b = gets.split.map &:to_i
  ns[a] += 1
  ns[b] += 1
}
m = ns.count(1)
puts m*(m-1)/2 >= N-1 ? "YES" : "NO"


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

def read_tokens
  return gets.chomp.to_s.strip.split(' ')
end

def read_ints
  data = []
  read_tokens.each { |s|
    data.push(s.to_i)
  }
  return data
end

n, = read_ints
doors = read_ints

def find_occ(arr, num)
  count = 0
  for el in arr
    if el == num
      count += 1
    end
  end
  return count
end

def solve(doors)
  k = 0
  zeros = find_occ(doors, 0)
  ones = find_occ(doors, 1)
  for i in 0...doors.length
    if zeros == 0 or ones == 0
      return k
    end
    if doors[i] == 0
      zeros -= 1
    elsif doors[i] == 1
      ones -= 1
    end
    k += 1
  end
  return k
end

print solve(doors)

n = gets.to_i
l = 0
r = 0
ds = gets.split.map(&:to_i)
lc = ds.count(0)
rc = ds.count(1)
ds.each_with_index do |i, ii|
  if i == 0
    l += 1
  else
    r += 1
  end
  if l == lc || r == rc
    puts ii + 1
    exit
  end
end

n = gets.to_i
a = gets.split.map(&:to_i)
(n-1).downto(1) do |i|
    if a[i] != a[i-1]
        puts i
        exit
    end
end

gets
a = gets.split
l, r = a.count('0'), a.count('1')
lo, ro = 0, 0
a.each_with_index do |x, i|
    if x == '0'
        lo += 1
    else
        ro += 1
    end
    if lo == l || ro == r
        puts i + 1
        exit
    end
end

n = gets.to_i
l = 0
r = 0
ans = 0
gets.split.map(&:to_i).each_with_index do |i, ii|
  if i == 0
    l += 1
  else
    r += 1
  end
  if r > 0 && l > 0 && r != l
    puts ii + 1
    exit
  end
end

n = gets.to_i
l = 0
r = 0
ans = 0
gets.split.map(&:to_i).each_with_index do |i, ii|
  if i == 0
    l += 1
  else
    r += 1
  end
  if r > 0 && l > 0
    puts ii + 1
    exit
  end
end


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

format = gets.to_i
hour, minute = gets.strip.split(":").map(&:to_i)
if format == 12 and hour == 0
  hour = 1
elsif format == 12 and hour > 12
  hour %= 10
  hour = 10 if hour == 0
elsif format == 24 and hour >= 24
  hour %= 10
end
if minute >= 60
  minute %= 10
end
puts "%02d:%02d" % [hour, minute]

#! /usr/bin/env ruby

form = gets.chomp
t = gets.split(?:)
h = t[0].to_i
m = t[1].to_i
#p form, h, m

t[1][0] = '0' if m > 59
if form == '24'
  t[0][0] = '0' if h > 23
else # form == 12
  if h == 0
    t[0] = '01'
  elsif h <= 12
    # do nothing
  else
    if t[0][1] == '0'
      t[0][0] = '1'
    else
      t[0][0] = '0'
    end
  end
end

puts t.join ?:

type = gets.to_i
h, m = gets.strip.split(":").map(&:to_i)

if m > 59
  m = m % 10
end

if type == 12
  if h < 1 || h > 12
    if h % 10 == 0
      h = 10
    else
      h = h % 10
    end
  end
else
  if h > 23
    h = h % 10
  end
end

puts "%02d:%02d"%[h,m]

t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if t == 12
  hh = hh % 10 if 12 < hh
  hh = 10 if hh == 0
elsif t == 24
  hh = hh % 10 if 23 < hh
end

puts '%02d:%02d' % [hh, mm]

kind = gets.to_i
time = gets.chomp
if time[3] >= '6'
  time[3] = '0'
end

poss = []
if kind == 24
  poss = (0 .. 23).map{|v| format("%02d", v)}
else
  poss = (1 .. 12).map{|v| format("%02d", v)}
end

mi = 100
mini = "indigo"

for p in poss
  s = time[0 .. 1]
  cnt = 0
  for i in 0 .. 1
    cnt += p[i] == s[i] ? 0 : 1
  end
  if mi > cnt
    mi = cnt
    mini = p
  end
end
time[0] = mini[0]
time[1] = mini[1]
puts time

t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if t == 12
  hh = hh % 10 if 12 < hh
  hh = 10 if hh == 0
else
  hh = hh % 10 if 24 < hh
end

puts '%02d:%02d' % [hh, mm]

t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if (t == 12 && hh == 0) || (t == 24 && hh == 24)
  hh = 12
elsif t < hh
  hh = hh % 10
end

puts "#{sprintf('%02d', hh)}:#{sprintf('%02d', mm)}"

t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if t == 12 && t == 0
  hh = 12
elsif t < hh
  hh = hh % 10
end

puts "#{sprintf('%02d', hh)}:#{sprintf('%02d', mm)}"

t = gets.chomp.to_i
hh, mm = gets.chomp.split(':').map(&:to_i)

mm = mm % 10 if 59 < mm
if t == 12
  if hh == 0
    hh = 1
  elsif 12 < hh
    hh = hh % 10
  end
else
  if 24 < hh
    hh = hh % 10
  end
end

puts "%02d:%02d" % [hh, mm]


There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.

The first line of input data contains two space-separated integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).

If the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue.  Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.

NoteIn the first sample test:  Before examination: {1, 2, 3}  After the first examination: {2, 3}  After the second examination: {3, 2}  After the third examination: {2} In the second sample test:  Before examination: {1, 2, 3, 4, 5, 6, 7}  After the first examination: {2, 3, 4, 5, 6, 7}  After the second examination: {3, 4, 5, 6, 7, 2}  After the third examination: {4, 5, 6, 7, 2, 3}  After the fourth examination: {5, 6, 7, 2, 3}  After the fifth examination: {6, 7, 2, 3, 5}  After the sixth examination: {7, 2, 3, 5, 6}  After the seventh examination: {2, 3, 5, 6}  After the eighth examination: {3, 5, 6, 2}  After the ninth examination: {5, 6, 2, 3}  After the tenth examination: {6, 2, 3}

n, k = gets.split.map{|_|_.to_i}
a = gets.split.map{|_|_.to_i}

b = a.sort
sum = a.inject{|x, y| x + y}
if sum < k
  puts -1
elsif sum == k
  puts
else
  i = 0
  s = 0
  while (b[i] - s) * (n - i) <= k
    k -= (b[i] - s) * (n - i)
    s = b[i]
    i += 1
  end
  while b[i] - s == 0
    i += 1
  end

  t = k / (n - i)
  k -= t * (n - i)

  j = 0
  while k > 0
    if a[j] >= b[i]
      a[j] -= 1
      k -= 1
    end
    j += 1
  end

  for k in j...n
    print((k + 1).to_s + " ") if a[k] > t + s
  end
  for k in 0...j
    print((k + 1).to_s + " ") if a[k] > t + s
  end
  puts
end

n, k = gets.split.map{|_|_.to_i}
a = gets.split.map{|_|_.to_i}

b = a.sort
if (a.length == 1 ? a[0] : a.inject{|x,y| x + y}) <= k
  puts -1
else
  i = 0
  s = 0
  while (b[i] - s) * (n - i) <= k
    k -= (b[i] - s) * (n - i)
    s = b[i]
    i += 1
  end
  while b[i] - s == 0
    i += 1
  end

  t = k / (n - i)
  k -= t * (n - i)

  j = 0
  while k > 0
    if a[j] >= b[i]
      a[j] -= 1
      k -= 1
    end
    j += 1
  end

  ans = ""
  for k in j...n
    if a[k] > t + s
      ans += (k + 1).to_s + " "
    end
  end
  for k in 0...j
    if a[k] > t + s
      ans += (k + 1).to_s + " "
    end
  end
  puts ans.strip
end

n, k = gets.split.map{|_|_.to_i}
a = gets.split.map{|_|_.to_i}

b = a.sort
if a.inject{|x,y| x + y} <= k
  puts -1
else
  i = 0
  s = 0
  while (b[i] - s) * (n - i) <= k
    k -= (b[i] - s) * (n - i)
    s = b[i]
    i += 1
  end
  while b[i] - s == 0
    i += 1
  end

  t = k / (n - i)
  k -= t * (n - i)

  j = 0
  while k > 0
    if a[j] >= b[i]
      a[j] -= 1
      k -= 1
    else
      a[j] = 0
    end
    j += 1
  end

  ans = ""
  for k in j...n
    if a[k] > t + s
      ans += (k + 1).to_s + " "
    end
  end
  for k in 0...j
    if a[k] > t + s
      ans += (k + 1).to_s + " "
    end
  end
  puts ans.strip
end


Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).A bill $$$x \times y$$$ fits into some wallet $$$h \times w$$$ if either $$$x \le h$$$ and $$$y \le w$$$ or $$$y \le h$$$ and $$$x \le w$$$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.Now you are asked to perform the queries of two types:  $$$+~x~y$$$ — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$. It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.For each query of type $$$2$$$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^5$$$) — the number of queries. Each of the next $$$n$$$ lines contains a query of one of these two types:   $$$+~x~y$$$ ($$$1 \le x, y \le 10^9$$$) — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ ($$$1 \le h, w \le 10^9$$$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$.  It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.

NoteThe queries of type $$$2$$$ of the example:  Neither bill fits;  Both bills fit (just checking that you got that bills can overlap);  Both bills fit (both bills are actually the same);  All bills fit (too much of free space in a wallet is not a problem);  Only bill $$$1 \times 5$$$ fit (all the others don't, thus it's "NO").

a, b = [0, 0]
gets.strip.to_i.times do
  q, l, r = gets.strip.split(' ')
  if q == '?'
    x = [l, r].map(&:to_i).sort
    puts a <= x[0] && b <= x[1] ? "YES" : "NO"
  else
    x = [l, r].map(&:to_i).sort
    a = [a, x[0]].max
    b = [b , x[1]].max
  end
end

DBG = true
n = gets.to_i
mx = 0
my = 0
for i in 0...n
  q,xx,yy = gets.split
  x = xx.to_i
  y = yy.to_i
  if x > y   # make x<=y
    z = x
    x = y
    y = z
  end
  if q == '+'
    mx = x if x > mx
    my = y if y > my
  else
    puts ((x >= mx && y >= my) ? "YES" : "NO")
  end
end

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

n = gets.to_i

maxone = 0
maxtwo = 0
n.times do
  q = gets.chomp.split(" ")
  if q[0]=="+"
    size = q[1..2].map(&:to_i).sort
    maxone = size[0] if size[0]>maxone
    maxtwo = size[1] if size[1]>maxtwo
  else
    size = q[1..2].map(&:to_i).sort
    if size[0]>=maxone and size[1]>=maxtwo
      puts "YES"
    else
      puts "NO"
    end
  end
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.

NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  cnt = [0,0,0]
  a.each do |v|
    cnt[v%3] += 1
  end
  k = (cnt[1]-cnt[2]).abs
  p cnt[0] + cnt[1,2].min + k/3
end

def solve(a)
  a = a.group_by do |e|
    e % 3 == 0 ? 0 : (e + 1) % 3 == 0 ? 1 : 2
  end
  one, two = a[1] || [], a[2] || []
  # puts one.inspect
  # puts two.inspect
  # puts a[0].inspect
  mn = [one.size, two.size].min
  mx = [one.size, two.size].max
  # puts mn
  # puts mx
  (a[0] || []).size + mn + ((mx - mn) / 3.0).to_i
end

gets.strip.to_i.times do |t|
  n = gets.strip.to_i
  a = gets.strip.split(' ').map(&:to_i)
  puts solve(a)
end


For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!  Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\frac{n \cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — volumes of cubes. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.

NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is "NO".

T = gets.to_i

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

  if a.each_cons(2).all? { |x, y| x > y }
    puts 'NO'
  else
    puts 'YES'
  end
end

t = gets.chomp.to_i

def solution(t)
  sorted, inversion_count = sort_inversion_count(t)
  return inversion_count
end

def sort_inversion_count(t)
  midpoint = t.length / 2
  left_half = t[0...midpoint]
  right_half = t[midpoint..t.length]

  if midpoint == 0
      return t, 0
  end

  sorted_left_half, left_half_inversion_count = sort_inversion_count(left_half)
  sorted_right_half, right_half_inversion_count = sort_inversion_count(right_half)

  sorted = []
  inversion_count = 0
  while sorted_left_half.length > 0 or sorted_right_half.length > 0
      if sorted_left_half.empty?
          sorted.push sorted_right_half.shift
      elsif sorted_right_half.empty?
          sorted.push sorted_left_half.shift
      else
          if sorted_left_half[0] > sorted_right_half[0]
              inversion_count += sorted_left_half.length
              sorted.push sorted_right_half.shift
          else
              sorted.push sorted_left_half.shift
          end
      end
  end

  return sorted, inversion_count + left_half_inversion_count + right_half_inversion_count
end

while t>0 do
  n = gets.chomp.to_i
  arr = gets.chomp.split(" ").map(&:to_i)
  threshold = (n*(n-1)/2) - 1

  inversions = solution(arr)
  res = inversions > threshold ? "NO" : "YES"

  puts res

  t -= 1
end