$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
$tries = {0 => [], 1 => []}

def find_max(eaten, last_eaten_type, current_jump_height)
  if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
    return
  end

  $tries[last_eaten_type][eaten.size] = current_jump_height

  available = (0..$candies_amount-1).to_a - eaten
  available_of_type = available.keep_if {|i| $candies[i][:type] != last_eaten_type }
  available_of_height = available_of_type.keep_if {|i| $candies[i][:height] <= current_jump_height}

  if available_of_height.length > 0
    # puts available_of_height.join(', ')
    max_weighted = $candies[available_of_height.first]
    find_max(eaten + [available_of_height.first], max_weighted[:type], current_jump_height + max_weighted[:weight])
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
$tries = {0 => [], 1 => []}
$ate = Array.new($candies_amount, false)

def find_max(eaten, last_eaten_type, current_jump_height)
  if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
    return
  end

  $tries[last_eaten_type][eaten.size] = current_jump_height

  to_eat_index = nil
  to_eat = nil
  $candies.each_with_index do |candy, i|
    if !$ate[i] && candy[:type] != last_eaten_type && candy[:height] <= current_jump_height
      to_eat_index = i
      to_eat = candy
      break
    end
  end

  if to_eat_index
    $ate[to_eat_index] = true
    find_max(eaten + [to_eat_index], to_eat[:type], current_jump_height + to_eat[:weight])
    $ate[to_eat_index] = false
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
# $tries = {0 => [], 1 => []}
$ate = Array.new($candies_amount, false)

def find_max(eaten, last_eaten_type, current_jump_height)
  # if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
  #   return
  # end

  # $tries[last_eaten_type][eaten.size] = current_jump_height

  to_eat_index = nil
  to_eat = nil
  $candies.each_with_index do |candy, i|
    if !$ate[i] && candy[:type] != last_eaten_type && candy[:height] <= current_jump_height
      to_eat_index = i
      to_eat = candy
      break
    end
  end

  if to_eat_index
    $ate[to_eat_index] = true
    find_max(eaten + [to_eat_index], to_eat[:type], current_jump_height + to_eat[:weight])
    $ate[to_eat_index] = false
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

n,x = readline.strip.split.map(&:to_i)

candies = [[],[]]
n.times{
  t,h,m = readline.strip.split.map(&:to_i)
  candies[t] << [h,m]
}

# all_candies.each{|candies| candies.sort_by!{|h,m| -h } }

def count_max_num(candies_group_now, candies_group_next_turn, height, count)
  # puts "(#{candies_group_now};  #{candies_group_next_turn};  #{height};  #{count})"
  target_candies = candies_group_now.select{|h,m| h <= height }
  # puts "  target:#{target_candies}"

  if target_candies.empty?
    # puts "count:#{count}"
    return count
  end

  h,m = target_candies.max_by{|h,m| m}
  idx = candies_group_now.index([h,m])

  count_max_num(candies_group_next_turn, candies_group_now.dup.tap{|cnd| cnd.delete_at(idx) }, height + m, count + 1)
end

puts [count_max_num(candies[0], candies[1], x, 0), count_max_num(candies[1], candies[0], x, 0)].max

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] > jump_height && t[:ate] > ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  # tries = $tries[last_eaten_type][index]
  # if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
  #   return
  # end

  # $tries[last_eaten_type][index] ||= []
  # $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, 1, initial_jump_height)
find_max(0, 0, 0, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  if last_eaten_type != $candies[index][:type] && jump_height >= $candies[index][:height]
    find_max(index+1, ate+1, $candies[index][:type], jump_height + $candies[index][:weight] )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate


#!/usr/bin/ruby

#read data
input_line = gets
params = input_line.split(' ')
n = params[0].to_i
k = params[1].to_i

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

#find max(a) and min(a)

if ((a.max - a.min)>k)
    puts 'NO'
else
    puts 'YES'
    a.each do |a_i|
        res = ''
        (0...a_i).each do |a_i_j|
          res += ((a_i_j % k)+1).to_s + ' '
        end
        puts res.strip
    end
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
# col = arr.map{|a| a/k}
a,b = arr.minmax
# puts "#{col.minmax}"
ans = true
ans = false if b  - a > k
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
# puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end
#

inp = gets.split(' ')
n = inp[0].to_i
m = inp[1].to_i

pebbles = gets.split(' ')
colors = Array.new() { Array.new() }
count = Array.new(n) { Array.new(m, 0) }

for i in 0..(n - 1)
	pebbles[i] = pebbles[i].to_i
	colors << Array.new(pebbles[i], 0)
end

for i in 0..(n - 1)
	color = 0
	for j in 0..(pebbles[i] - 1)
		colors[i][j] = color
		count[i][color] += 1
		color += 1
		if color >= m
			color = 0
		end
	end
	for j in 0..(i - 1)
		for k in 0..(m - 1)
			if (count[j][k] - count[i][k]).abs > 1
				puts "NO"
				exit
			end
		end
	end
end

puts "YES"
colors.each { |arr|
	arr.each { |el|
		print "#{el + 1} "
	}
	puts
}

pa = Array.new
pb = Array.new
data = Array.new

str = gets.to_s
stt = gets.to_s
pa = str.split
pb = stt.split
n = pa[0].to_i
k = pa[1].to_i

for i in 0..n-1
  data[i]=Array.new
  r = pb[i].to_i / k
  t = pb[i].to_i % k
  for j in 1..k
    if j <= t
      data[i][j] = r + 1
    else
      data[i][j] = r
    end
  end
end

flag = 0
for j in 1..k
   min = max = data[0][j]
   for i in 1..n-1
     if min > data[i][j]
       min = data[i][j]
     end
     if max < data[i][j]
       max = data[i][j]
     end
   end
   if max - min > 1
     flag = 1
     break
   end
end

if flag == 1
  puts "NO"
else
  puts "YES"
  for i in 0..n-1
    flag = 0
    for j in 1..k
      for r in 1..data[i][j]
        if flag == 0
          print j
          flag = 1
        else
          print " "
          print j
        end
      end
    end
    puts
  end
end

#!/usr/bin/env ruby
n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
b=a.map{|e|
	h=Hash.new(0)
	z=e.times.map{|i|
		n=i%k+1
		h[n]+=1
		n
	}
	[z,h]
}
if b.combination(2).all?{|x,y|
	(1..k).all?{|e|(x[1][e]-y[1][e]).abs<=1}
}
	puts :YES
	puts b.map{|e|e[0]*' '}
else
	puts :NO
end

n,k=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
max,min=a.max,a.min
if max-min>k
	puts "NO"
else
	puts "YES"
	n.times do |i|
		j=0
		while j<a[i]
			print "#{(j%k)+1} "
			j+=1
		end
		puts
	end
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  if i == 0
    min = a.min + 1
  else
    min = 1
  end

  n.times do |j|
    min.times do |k|
      if a[j] != 0
        colors[j] << i + 1
        a[j] -= 1
      end
    end
  end
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  puts 'NO'
else
  puts 'YES'
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  min = (a.select { |x| x != 0}).min

  n.times do |j|
    min.times do |k|
      colors[j] << i + 1 if a[j] != 0
    end
  end

  break if min == 0

  a = a.map { |x| x == 0 ? 0 : x - min }
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  if i == 0
    min = a.min
  else
    min = 1
  end

  n.times do |j|
    min.times do |k|
      colors[j] << i + 1 if a[j] != 0
    end
  end

  a = a.map { |x| x == 0 ? 0 : x - min }
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  p 'NO'
else
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  p 'NO'
else
  p 'YES'
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

#!/usr/bin/ruby

#read data
input_line = gets
params = input_line.split(' ')
n = params[0].to_i
k = params[1].to_i

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

#find max(a) and min(a)

if ((a.max - a.min)>k)
    puts 'NO'
else
    puts 'YES'
    res = ''
    a.each do |a_i|
        res += ((a_i % k)+1).to_s + ' '
        puts res.strip
    end
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
# col = arr.map{|a| a/k}
a,b = arr.minmax
# puts "#{col.minmax}"
ans = true
ans = false if b  - a > k
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
col = arr.map{|a| a/k}
a,b = col.minmax
ans = true
ans = false if b  - a > 1
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
# puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end

#!/usr/bin/ruby

n = gets.to_i
m = gets.to_i

pebbles = Array.new(n)
colors = Array.new() { Array.new() }
count = Array.new(n) { Array.new(m, 0) }

for i in 0..(n - 1)
	pebbles[i] = gets.to_i
	colors << Array.new(pebbles[i], 0)
end

for i in 0..(n - 1)
	color = 0
	for j in 0..(pebbles[i] - 1)
		colors[i][j] = color
		count[i][color] += 1
		color += 1
		if color >= m
			color = 0
		end
	end
	for j in 0..(i - 1)
		for k in 0..(m - 1)
			if (count[j][k] - count[i][k]).abs > 1
				puts "NO"
				exit
			end
		end
	end
end

puts "YES"
colors.each { |arr|
	arr.each { |el|
		print "#{el + 1} "
	}
	puts
}

#!/usr/bin/ruby

if __FILE__ == $0

	n = ARGV[0].to_i
	m = ARGV[1].to_i

	pebbles = Array.new(n)
	colors = Array.new() { Array.new() }
	count = Array.new(n) { Array.new(m, 0) }

	for i in 2..(n + 1)
		pebbles[i - 2] = ARGV[i].to_i
		colors << Array.new(pebbles[i - 2], 0)
	end

	for i in 0..(n - 1)
		color = 0
		for j in 0..(pebbles[i] - 1)
			colors[i][j] = color
			count[i][color] += 1
			color += 1
			if color >= m
				color = 0
			end
		end
		for j in 0..(i - 1)
			for k in 0..(m - 1)
				if (count[j][k] - count[i][k]).abs > 1
					puts "NO"
					exit
				end
			end
		end
	end

	puts "YES"
	colors.each { |arr|
		arr.each { |el|
			print "#{el + 1} "
		}
		puts
	}

end


ans = 0
gets
gets.split('').each_with_index{|x, i|
    ans += i + 1 if ['0', '2', '4', '6', '8'].include? x
}
puts ans

n = gets.to_i
s = gets.chomp.chars.map(&:to_i)
ans = 0
(0..n-1).each do |i|
  if s[i].even?
    ans += i + 1
  end
end
puts ans

n = gets.to_i
s = gets
ans = 0
n.times do |i|
  if /[02468]/ =~ s[i]
    ans += i+1
  end
end
puts ans

require 'enumerator'
gets
s = gets;
puts s.enum_for(:scan, /[2468]/)
      .map { Regexp.last_match.begin(0) + 1 }
      .inject(0) {|r, p| r + p}


def solve
  n = gets.to_i
  a = gets.split.map(&:to_i)
  m = a.min
  puts a.count { |x| x > m }
end

t = gets.to_i
t.times do
  solve
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(" ").map(&:to_i)
  arr.delete(arr.min)
  puts arr.size
end

def solution(n, arr)
	average = arr.sum / n

	removed = true
	result = 0

	while removed
		i = 0
		removed = false

		while i < n
			if arr[i] > average
				arr.delete_at(i)
				n -= 1
				result += 1
				removed = true

				average = arr.sum / n
			end

			i += 1
		end
	end

	result
end

test_cases = gets.to_i

test_cases.times do
  n = gets.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  puts solution(n, arr)
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }.sort
  i = 0
  i += 1 while a[i] == a[0]
  printf("%d\n", a.size - i)
end


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

if str == str.sort
  puts :NO
else
  (n - 1).times do |i|
    if str[i] > str[i + 1]
      right = i + 1
      left = i
      while str[left] <= str[right]
        left -= 1
      end
      puts :YES, [left + 1, right + 1].join(' ')
    break
    end
  end
end

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 0
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != -1
	puts "YES"
	puts "#{low} #{high}"
else
	puts "NO"
end

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 1
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != -1
	puts "YES"
	puts "#{low} #{high}"
else
	puts "NO"
end

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 1
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != "-1"
	p "YES"
	p "#{low} #{high}"
else
	p "NO"
end


t = gets

t = t.to_i

(1..t).each do |e|
    inp = gets
    inp = inp.split(' ').map(&:to_i)
    a = gets
    a = a.split(' ').map(&:to_i)
    a.sort!
    #puts "{a: #{a}"
    cur = 0
    res = 0
    a.each do |x|
        if (cur+x) <= inp[3]
            if x >= inp[1] && x <= inp[2]
                cur += x
                res += 1
            end
        else
            break
        end
    end

    puts res
end

gets.to_i.times do
  n, l, r, k = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  p as.sort.select { |a| a >= l && a <= r }.take_while { |a| k -= a; k >= 0 }.size
end


def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  i = 0
  while i < s.size
    if s[i] == s[i + 1]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
    i += 1
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

1.upto(gets.to_i) do
  s = gets.chomp

  same = s.chars.all? { |c| s[0] == c }

  while !same
    ll = s.length
    s.gsub!('00', '010')
    s.gsub!('11', '101')

    break if ll == s.length
  end

  puts s
end

gets.to_i.times {
    t=gets.chomp.chars
    if t.uniq.size==1
        s=t*''
    else
        s=t.shift
        t.each{|c|
            s+=(c==?0 ? ?1 : ?0) if s[-1]==c
            s+=c
        }
    end
    puts s
}

1.upto(gets.chomp.to_i) do
  t = gets.chomp
  at = t.split(//)
  if at.uniq.size == 1
    puts t
  else
    puts "01"*t.size
  end
end

tttt = gets.chomp.to_i

# 周期性
def chkPeriod(str)
	(1..str.length/2).each do |i|
		ngo = str.chars.each_slice(i).to_a
		return i if ngo.uniq.length == 1
	end
	return -1
end

#sがtのサブシーケンスか
def chkSubsequence(s, t)
	si = 0
	ti = 0
	while si < s.length || ti < t.length
		return false if si >= s.length
		return true if ti >= t.length
		if s[si] == t[ti] then
			ti += 1
		end
		si += 1
	end
end

tttt.times do
	t = gets.chomp
	if t.chars.uniq.length == 1 then
		puts t
		next
	end

	# 次にどの文字をぶちこむか(true→1 false→0)
	str = ""
	i = 0
	while i < t.length
		if t[i+1] != t[i] && i < t.length - 1 then
			str += t[i]
			i += 1
			next
		end
		str += t[i]
		str += t[i] == "0" ? "1" : "0"
		i += 1
	end
	#puts str
	str = str[0] != str[-1] ? str : str.slice(0,str.length - 1)
	puts str
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  (0..s.size).to_a.each do |i|
    if s[i] != s[i + 2] && s[i + 2]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  "10" * (s.size / 2)
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  chars.size.times do |i|
    if s[i] == s[i + 1]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  chars.size.times do |i|
    next if i == 0
    if s[i] == s[i-1]
      s.insert(i, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  (0..chars.size).to_a.each do |i|
    if s[i] != s[i + 2] && s[i + 2]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end


x , k = gets.strip.split(' ').map(&:to_i);
n = gets.chomp
c = 0
l = 0
best = 0
for i in 0 ... x
  if (n[i] != 'a')
    c+=1
  end
  while(c > k)
    if (n[l] == 'b')
      c-=1
    end
    l+=1
  end
  best = [best , i - l + 1].max
end
c = 0
l = 0
for i in 0 ... x
  if (n[i] != 'b')
    c+=1
  end

  while(c > k)
    if (n[l] == 'a')
      c-=1
    end
    l+=1
  end
  best = [best , i - l + 1].max
end
puts best

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count > k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[i] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count > k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[pos] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count == k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[pos] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans


gets.to_i.times do
    a, b = gets.split.map &:to_i
    if a == 0
        puts 0
        next
    end
    res, i = a + 3, b < 2 ? 2 - b : 0
    while i < res do
        ca, cur = a, i
        while ca > 0 do
            ca /= b + i
            cur += 1
        end
        res = [res, cur].min
        i += 1
    end
    puts res
end

def method(a, b)
  if b == 1
    return 100
  end
  res = 0
  while a != 0
    a /= b
    res += 1
  end
  res
end

t = gets.to_i
t.times do
  a, b = gets.split.map { |x| x.to_i }
  puts (0..30).map { |x| method(a, b + x) + x }.min
end

gets.to_i.times do
  a,b=gets.split.map(&:to_i)
  c=0
  if b==1
    b+=1
    c+=1
  end
  cmin=1/0.0
  cc=c
  bb=b
  aa=a
  while true
    a=aa
    b=bb
    c=cc
    while a>b
      a=a/b
      c+=1
    end
    c+=1 if a==b
    if c+1<=cmin
      cmin=c+1
    else
      puts cmin
      break
    end
    bb+=1
    cc+=1
  end
end


T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  cur = 0
  len = 0

  a.reverse_each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  sum = a.inject(:+)

  if var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
#  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
#  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
   #  puts sum.to_s + "   " + a.to_s
    return true unless sum > 0
  end
  false
end

n = gets
n.to_i.times { one_test }

T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0
  max_len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur
      max_len = len
      var = cur
    end
  end

  sum = a.inject(:+)

  if max_len < n && var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  sum = a.inject(:+)

  if var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
    if a <= 0
      return true
    end
  end
  false
end

n = gets
n.to_i.times { one_test }

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
#  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
#  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
    if a <= 0
      return true
    end
  end
  false
end

n = gets
n.to_i.times { one_test }


zeros = ->n {
  count = 0
  while n % 10 == 0
    count += 1
    n /= 10
  end
  count
}

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  o = 1
  o *= 2 while o * 2 < m && zeros[n * o * 2] > zeros[n * o]
  o *= 5 while o * 5 < m && zeros[n * o * 5] > zeros[n * o]
  o *= 10 while o * 10 < m && zeros[n * o * 10] > zeros[n * o]
  o *= m / o
  p n * o
end

zeros = ->n { n.to_s.reverse.chars.take_while { |c| c == "0" }.size }

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  o = 1
  o *= 2 while o * 2 < m && zeros[n * o * 2] > zeros[n * o]
  o *= 5 while o * 5 < m && zeros[n * o * 5] > zeros[n * o]
  o *= 10 while o * 10 < m && zeros[n * o * 10] > zeros[n * o]
  o *= m / o
  p n * o
end

gets.to_i.times do
    n,m=gets.chomp.split(' ').map(&:to_i)
    factor=1
    t=n
    while t%10==0 do
        t/=10
    end
    while t%2==0 && factor*5 <= m do
        t/=2
        factor*=5
    end
    while t%5==0 && factor*2 <= m do
        t/=5
        factor *=2
    end
    while factor*10<=m
        factor*=10
    end
    puts n*(m-m%factor)
end


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.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

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


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


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


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


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(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)
	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


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


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.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.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

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

#!/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


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

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()
  tmp = res[0][1]
  res.each do |r|
    puts [[r[0], tmp].min, r[1]].join(" ")
    tmp = r[1] + 1
  end
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 - 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


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,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=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 = $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


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"


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

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


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]


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


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

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


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


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


n,m = gets.chomp.split.map{|x| x.to_i}

candidate_wins = Array.new(n+1){0}
#cities
(0...m).each do |i|
	arr = gets.chomp.split.map{|x| x.to_i}
	curr_winner = 0
	curr_max_votes = -1
	(0...n).each do |j|
		if arr[j] > curr_max_votes
			curr_max_votes = arr[j]
			curr_winner = j
		end
	end
	candidate_wins[curr_winner+1]+=1
end
overall_winner = 0
over_all_win = -1
(1..n).each do |i|
	if candidate_wins[i] > over_all_win
		overall_winner = i
		over_all_win = candidate_wins[i]
	end
end

puts overall_winner

n,m = gets.split.map(&:to_i)
a = Array.new(n,0)
x,y = -1,0
m.times do |j|
	t = gets.split.map(&:to_i)
	for i in 0...n
		if t[i] > x
			x = t[i]
			y = i
		end
	end
	a[y] += 1
	x,y = -1,0
end
for i in 0...n
	if a[i] > x
		x = a[i]
		y = i
	end
end
p y+1

n, m = gets.chomp.split("\s").map(&:to_i)
a = m.times.map { gets.chomp.split("\s").map(&:to_i) }

winners = a.map do |votes_by_city|
  votes_by_city.find_index(votes_by_city.max)
end

puts winners.sort.max_by { |e| winners.count(e) } + 1

n,m=gets.split.map &:to_i;c=[0]*n;m.times{l=gets.split.map &:to_i;c[l.index(l.max)]+=1};p c.index(c.max)+1

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

vt = Array.new(n) { 0 }
max_votes = 0
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        if i < max
            #pass
        elsif i == max
            maxs << index
        else
            maxs.clear
            max = i
            maxs << index
        end
    }
    vt[maxs.first] += 1
    if max_votes < vt[maxs.first]
        max_votes = vt[maxs.first]
    end
}
for index in 0...n
    if max_votes == vt[index]
        puts (index + 1) # 1-based index
        break
    end
end

n, m = gets.split(' ').map(&:to_i)
votes_in_cities = Array.new(n, 0)
m.times do
  tmp = gets.split(' ').map(&:to_i)
  vinner_in_city = tmp.index(tmp.max)
  votes_in_cities[vinner_in_city] += 1
end

puts votes_in_cities.index(votes_in_cities.max) + 1

n, m = gets.split.map(&:to_i)
a = m.times.map{gets.split.map(&:to_i)}
b = a.map{|x| x.index(x.max)}.sort
puts b.group_by{|x| x}.to_a.max_by{|x| x[1].length}[0] + 1

n, m = gets.split.map{|x| x.to_i}
c = [0]*n
m.times do
    a = gets.split.map{|x| x.to_i}
    c[a.find_index(a.max)] += 1
end
puts(c.find_index(c.max) + 1)

n, m = gets.chomp.split(' ').map { |i| i.to_i }
selected = []
count = Array.new(if n > m then n else m end) { |i| i = 0 }

m.times do
	candidates = gets.chomp.split(' ').map { |i| i.to_i }
	# find Max, put in array
	selected << candidates.index(candidates.max)
end

selected.each do |v|
	count[v] = selected.count(v)
end

puts count.index(count.max) + 1

#!/usr/bin/ruby
N,M=gets.to_i
A=$<.map{|e|e.split.map(&:to_i)}
h=Hash.new(0)
A.each{|e|h[e.each_with_index.map{|x,i|[-x,i]}.min[1]]+=1}
p h.min_by{|k,v|[-v,k]}[0]+1

n,m = gets.split(" ").map(&:to_i)
cand = [0]*n
for i in (1..m)
   li = gets.split(" ").map(&:to_i)
   cand[li.index(li.max)]+=1
end
puts cand.index(cand.max) + 1

# http://codeforces.com/contest/570/problem/A
n, m = gets.chomp.split.map(&:to_i)
array = Array.new(n) { 0 }

m.times do
  votes = gets.chomp.split.map(&:to_i)
  max = votes.max

  array[votes.index(max)] += 1
end

max = array.max
puts array.index(max) + 1

n, m = gets.split(' ').map{|x| x.to_i}
res = []
m.times do |x|
	res[x] = gets.split.map{|x| x.to_i}
	res[x] = res[x].index(res[x].max)

end

count = []
for i in 0...n
	count[i] = res.count(i)
end

puts count.index(count.max)+1

n, m = gets.split(" ").map(&:to_i)
a = Array.new(n){0}
m.times{
  voices = gets.split(" ")
  best = 0
  voices.each_index { |i| best = voices[i].to_i>voices[best].to_i ? i : best}
  a[best] += 1
}
best = 0
a.each_index { |i| best = a[i]>a[best] ? i : best}
puts best+1

c=(0..100).map{0}
n,m=gets.split.map{|e| e.to_i}
m.times{
	x=gets.split.map{|e| e.to_i}
	c[x.index(x.max)+1]+=1
}
p c.index(c.max)

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| [city_winners.count(i),-i] }+1

n,m = gets.chomp.split.map{|x| x.to_i}

candidate_wins = Array.new(n+1){-1}
#cities
(0...m).each do |i|
	arr = gets.chomp.split.map{|x| x.to_i}
	curr_winner = -1
	curr_max_votes = -1
	(0...n).each do |j|
		if arr[j] > curr_max_votes
			curr_max_votes = arr[j]
			curr_winner = j
		end
	end
	candidate_wins[curr_winner+1]+=1
end
overall_winner = -1
over_all_win = 0
(1..n).each do |i|
	if candidate_wins[i] > over_all_win
		overall_winner = i
		over_all_win = candidate_wins[i]
	end
end

puts overall_winner

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| [city_winners.count(i),-i] }[0]+1

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| city_winners.count( i ) }+1

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

# 1st
vt = Array.new(n) { 0 }
vt2 = Array.new(n) { 0 }
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        vt[index] += i
        if max < vt[index]
            maxs.clear
            max = vt[index]
            maxs << index
        elsif max == vt[index]
            maxs << index
        else
            # pass
        end
    }
    vt2[maxs.pop] += 1
}

max_vote = vt2.max
for index in 0...n
    if vt2[index] == max_vote
        puts (index + 1) # 1-based index
        break
    end
end

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

# 1st
vt = Array.new(n) { 0 }
vt2 = Array.new(n) { 0 }
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        vt[index] += i
        if max < vt[index]
            maxs.clear
            max = vt[index]
            maxs << index
        elsif max == vt[index]
            maxs << index
        else
            # pass
        end
    }
    vt2[maxs.first] += 1
}

max_vote = vt2.max
for index in 0...n
    if vt2[index] == max_vote
        puts (index + 1) # 1-based index
        break
    end
end

n, m = gets.split.map(&:to_i)
a = m.times.map{gets.split.map(&:to_i)}
b = a.map{|x| x.index(x.max)}
puts b.group_by{|x| x}.to_a.max_by{|x| x[1].length}[0] + 1


def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("i", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def get_login
  s = gets
  s.gsub(/0{1}/, 'o').gsub(/[lLIi]{1}/, '1').downcase
end

new_login = get_login
n = gets.to_i
n.times do
  if new_login == get_login
    puts 'No'
    exit
  end
end

puts 'Yes'

def simplify(string)
	str_arr = string.split("")
	str_copy = str_arr
	str_arr.each_with_index do |char, index|
		case char
		when 'O', 'o'	#big ou
			str_copy[index] = 0
		when 'l', 'I', 'L', 'i'
			str_copy[index] = 1
		else
			str_copy[index] = char
		end
	end
	str_copy.join('').downcase
end

wanted_login = gets.chomp
number = gets.chomp
logins = []

if wanted_login.length <= 50 && (number.to_i >= 1 && number.to_i <= 1000)
	all_logins_passed = true

	number.to_i.times do
		if all_logins_passed
			logins << gets.chomp
		end
	end

	logins.each do |curent_login|
		all_logins_passed = false if curent_login.length > 50
	end

	if all_logins_passed
		user_can_register = true

		logins.each do |existed_login|
			if simplify(existed_login).eql? simplify(wanted_login)
				user_can_register = false
			end
		end

		puts 'Yes' if user_can_register
		puts 'No' unless user_can_register
	end
end

def modify(s)
    s.gsub!("1", "l")
    s.gsub!("I", "l")
    s.gsub!("0", "o")
    s.downcase!
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def modify(s)
    s.gsub!("1", "l")
    s.gsub!("i", "l")
    s.gsub!("0", "o")
    s.downcase!
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def simplify(string)
	str_arr = string.split("")
	str_copy = str_arr
	str_arr.each_with_index do |char, index|
		case char
		when 'O', 'o'	#big ou
			str_copy[index] = 0
		when 'l', 'I', 'L', 'i'
			str_copy[index] = 1
		else
			str_copy[index] = char
		end
	end
	str_copy.join('').downcase
end

wanted_login = gets.chomp
number = gets.chomp
logins = []

if wanted_login.length <= 50 && (number.to_i > 1 && number.to_i < 1000)
	all_logins_passed = true

	number.to_i.times do
		if all_logins_passed
			logins << gets.chomp
		end
	end

	logins.each do |curent_login|
		all_logins_passed = false if curent_login.length > 50
	end

	if all_logins_passed
		user_can_register = true

		logins.each do |existed_login|
			if simplify(existed_login).eql? simplify(wanted_login)
				user_can_register = false
			end
		end

		puts 'Yes' if user_can_register
		puts 'No' unless user_can_register
	end
end

def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("I", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"


n = gets.to_i
m = n / 3
a = gets.chomp.chars.map(&:to_i)
cnt = (0...3).map { a.count(_1) }

2.times do
	a.each_with_index do |from, i|
		(0...from).each do |to|
			if cnt[from] > m && cnt[to] < m
				a[i] = to
				cnt[from] -= 1
				cnt[to] += 1
				break
			end
		end
	end
	a = a.reverse.map { 2 - _1 }
	cnt.reverse!
end
puts a.join

n = gets.to_i
s = gets.chomp.split("").map(&:to_i)
a = [0,0,0]
n.times do |i|
    a[s[i]] += 1
end
if a[0] < n/3
    n.times do |i|
        next if s[i] == 0 || a[s[i]] <= n/3
        a[0] += 1
        a[s[i]] -= 1
        s[i] = 0
        break if a[0] == n/3
    end
end
if a[1] < n/3
    n.times do |i|
        next if s[i] < 2
        a[1] += 1
        a[2] -= 1
        s[i] = 1
        break if a[1] == n/3
    end
end
if a[2] < n/3
    n.times do |i|
        next if s[-1-i] == 2 || a[s[-1-i]] <= n/3
        a[2] += 1
        a[s[-1-i]] -= 1
        s[-1-i] = 2
        break if a[2] == n/3
    end
end
if a[1] < n/3
    n.times do |i|
        next if s[-1-i] > 0
        a[1] += 1
        a[0] -= 1
        s[-1-i] = 1
        break if a[1] == n/3
    end
end
puts s.join("")


n = gets.to_i

n.times do
  m = gets.chomp

  p (m.to_i - (10 ** (m.size - 1)))
end

def round_down_price(num)
  len = num.digits.count
  round = 10**(len-1)
  extra = num - round
  extra
end

t = gets.chomp.to_i
input = []
(0..t-1).each do |i|
  input.push(gets.chomp.to_i)
end

input.each do |i|
  p round_down_price(i)
end

t = gets.to_i
t.times {
  n = gets.chomp
  if n == 0
    puts "0"
  else
    n[0] = (n[0].ord - 1).chr
    puts n.to_i
  end
}

gets.to_i.times { m = gets.strip; puts m.to_i - 10 ** (m.size - 1)}

gets.to_i.times { m = gets; puts m.to_i - 10 ** (m.size - 1)}


def comb(n,k)
	r=1
	k.times{|i|
		r=r*(n-i)/(i+1)
	}
	r
end
n=gets.to_i
p comb(n,5)+comb(n,6)+comb(n,7)