Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls.  Each of the following n lines contains information about a foul in the following form:    first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.  The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

For each event when a player received his first red card in a chronological order print a string containing the following information:   The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.  If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
processed = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    if !processed[[team,player]]
      result << [team,player,m.to_i]
      processed[[team,player]] = true
    end
  else
    if hash[[team,player]]
      if !processed[[team,player]]
        result << [team,player,m.to_i]
        processed[[team,player]] = true
      end
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

team_a = STDIN.readline.strip
team_b = STDIN.readline.strip
n = STDIN.readline.to_i
yellow, red = {}, {}
n.times do
  tokens = STDIN.readline.split
  time, player, color = tokens[0].to_i, tokens[2].to_i, tokens[3]
  team = tokens[1] == 'h' ? team_a : team_b
  key = [player, team]
  first_red = false
  if color == 'y'
    if yellow.include?(key) and not red.include?(key)
      red[key] = first_red = true
    end
    yellow[key] = true
  else
    if not red.include?(key)
      red[key] = first_red = true
    end
  end
  if first_red
    puts '%s %d %d' % [team, player, time]
  end
end

require 'pp'

teama = STDIN.gets.chomp
teamb = STDIN.gets.chomp

h ={teama => {}, teamb => {}}

n = STDIN.gets.chomp.to_i

n.times do
  t, ha, num, yr = STDIN.gets.chomp.split(/ /)
  team = ha == 'h' ? teama : teamb

  if h[team].has_key?(num) && h[team][num] == 2
    # nothing
  elsif h[team].has_key?(num) && h[team][num] == 1
    print "#{team} #{num} #{t}\n"
      h[team][num] = 2
  elsif !h[team].has_key?(num)
    if yr == 'r'
      print "#{team} #{num} #{t}\n"
      h[team][num] = 2
    else
      h[team][num] = 1
    end
  end
end

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

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    if @card != 'r'
      @time = p.time
      @card = 'r'
    end
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end

    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.red_card_list.each do |p|
  t = p.team == "a" ? a : h
  puts "#{t} #{p.b_num} #{p.time}"
end

name=[gets.chomp,gets.chomp]
foul=[{},{}]
done=[{},{}]
gets.to_i.times{
  time,team,n,type=gets.split
  team_n=team==?h?0:1
  if foul[team_n][n] || type==?r
    unless done[team_n][n]
      puts [name[team_n],n,time]*" "
      done[team_n][n]=true
    end
  else
    foul[team_n][n]=true
  end
}

home_team = gets.chomp
away_team = gets.chomp
N = gets.to_i
used = {}
red = {}
while $_ = gets do
    t_, team, m_, type = $_.split
    t = t_.to_i
    m = m_.to_i
    if red["#{team}:#{m}"]
        next
    end
    if type == "r" || used["#{team}:#{m}"] then
        if team == "h"
            print home_team
        else
            print away_team
        end
        print " #{m} #{t}\n"
        red["#{team}:#{m}"] = true
    end
    used["#{team}:#{m}"] = true
end

#!/usr/bin/ruby
home = STDIN.gets.chomp
away = STDIN.gets.chomp
n = STDIN.gets.chomp.to_i
marked = {'a' => [], 'h' => []}
teams = {'a' => away, 'h' => home}
n.times do
    tokens = STDIN.gets.chomp.split(' ')
    minute = tokens[0].to_i
    team = tokens[1]
    player = tokens[2].to_i
    card = tokens[3]
    marked[team][player] = 0 if not marked[team][player]
    next if marked[team][player] > 1
    if card == 'r' or marked[team][player] == 1
        marked[team][player] = 2
        puts "#{teams[team]} #{player} #{minute}"
    else
        marked[team][player] += 1
    end
end

a=Array.new(105,0)
b=Array.new(105,0)
sz=Array.new
sta=gets.to_s
stb=gets.to_s
n=gets.to_i
for i in 1..n
  stc=gets.to_s
  sz=stc.split
  if sz[3]=='y'
    tr=1
  elsif sz[3]=="r"
    tr=2
  end
  if sz[1]=="h"
    t=sz[2].to_i
    if a[t]>=2
      next
    end
    a[t]+=tr
    if a[t]>=2
      print sta.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  elsif sz[1]=="a"
    t=sz[2].to_i
    if b[t]>=2
      next
    end
    b[t]+=tr
    if b[t]>=2
      print stb.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  end
end

# 493A

class Foul
  include Comparable
  attr :time

  def initialize(player, time, team)
    @player = player
    @time = time.to_i
    @team = team
  end

  def <=>(another)
    time <=> another.time
  end

  def to_s
    [@team, @player, @time].join(' ')
  end
end

names = {h: gets.chomp, a: gets.chomp}
cards = {h: {y: {}, r: {}}, a: {y: {}, r: {}}}
gets.to_i.times do
  time, _team, player, card_colour = gets.chomp.split
  team = _team.to_sym
  unless cards[team][:r].include?(player)
    if card_colour == 'r'
      cards[team][:r][player] = time
    else
      if cards[team][:y].include?(player)
        cards[team][:r][player] = time
      else
        cards[team][:y][player] = time
      end
    end
  end
end

fouls = []
[:h, :a].each { |c| cards[c][:r].each { |k, v| fouls << Foul.new(k, v, names[c]) } }
fouls.sort.each { |foul| puts foul }

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end

    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end

    if a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end

    if a[arry[i][1]][arry[i][2]] == nil
      a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
    end

  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  if a[arry[i][1]][arry[i][2]] == nil
    a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
  end
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
  else
    if hash[[team,player]]
      result << [team,player,m.to_i]
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
    hash.delete([team,player]) if hash[[team,player]]
  else
    if hash[[team,player]]
      result << [team,player,m.to_i]
      hash.delete([team,player])
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m]
  else
    if hash[[team,player]]
      result << [team,player,m]
    else
      hash[[team,player]] = true
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

h = gets.chomp
a = gets.chomp
n = gets.to_i
hash = {}
result = []
n.times do
  m,team,player,card = gets.chomp.split
  if card == 'r'
    result << [team,player,m.to_i]
  else
    if hash[[team,player]]
      result << [team,player,[m.to_i,hash[[team,player]]].max]
    else
      hash[[team,player]] = m.to_i
    end
  end
end
result = result.sort_by {|x| x[2]}
result.each do |team,player,minute|
  puts "#{team == 'h' ? h : a} #{player} #{minute}"
end

team_a = STDIN.readline.strip
team_b = STDIN.readline.strip
n = STDIN.readline.to_i
foul = {}
n.times do
  tokens = STDIN.readline.split
  time, player, color = tokens[0].to_i, tokens[2].to_i, tokens[3]
  team = tokens[1] == 'h' ? team_a : team_b
  key = [player, team]
  if color == 'y'
    if foul[key] == 1
      puts '%s %d %d' % [team, player, time]
      foul[key] += 1
    else
      foul[key] = 1
    end
  else
    if not foul.include? key
      puts '%s %d %d' % [team, player, time]
      foul[key] = 2
    else
      if foul[key] == 1
        puts '%s %d %d' % [team, player, time]
      end
      foul[key] += 1
    end
  end
end

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

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    @time = p.time
    @card = 'r'
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end
    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.each do |p|
  if p.card == "r"
    t = p.team == "a" ? a : h
    puts "#{t} #{p.b_num} #{p.time}"
  end
end

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

class Player
  attr_reader :time, :team, :b_num, :card

  def initialize(l)
    @time  = l[0].to_i
    @team  = l[1]
    @b_num = l[2].to_i
    @card  = l[3]
  end

  def update(p)
    @time = p.time
    @card = 'r'
  end

end

class Players
  def initialize
    @faul_receivers = []
  end

  def <<(p)
    if @faul_receivers.length < 1
      @faul_receivers << p
    else
      update = false
      @faul_receivers.each do |r|
        update= true if r.team == p.team and r.b_num == p.b_num
        if update
          r.update(p)
          break
        end
      end
      @faul_receivers << p unless update
    end
  end

  def red_card_list
    reds = []
    @faul_receivers.each do |p|
      reds << p if p.card == 'r'
    end

    reds.sort_by! { |p| p.time }
    return reds
  end

  def each(&block)
    @faul_receivers.each &block
  end
end

h, a, n = gets.chomp, gets.chomp, gets.chomp.to_i

p_l = Players.new
n.times do
  l = gets.chomp.split(' ')
  p = Player.new(l)
  p_l << p
end

p_l.red_card_list.each do |p|
  t = p.team == "a" ? a : h
  puts "#{t} #{p.b_num} #{p.time}"
end

home_team = gets.chomp
away_team = gets.chomp
N = gets.to_i
used = {}
while $_ = gets do
    t_, team, m_, type = $_.split
    t = t_.to_i
    m = m_.to_i
    if type == "r" || used["#{team}:#{m}"] then
        if team == "h"
            print home_team
        else
            print away_team
        end
        print " #{m} #{t}\n"
    end
    used["#{team}:#{m}"] = true
end

a=Array.new(105,0)
b=Array.new(105,0)
sz=Array.new
sta=gets.to_s
stb=gets.to_s
n=gets.to_i
for i in 1..n
  stc=gets.to_s
  sz=stc.split
  if sz[3]=='y'
    tr=1
  elsif sz[3]=="r"
    tr=2
  end
  if sz[1]=="h"
    t=sz[2].to_i
    a[t]+=tr
    if a[t]>=2
      print sta.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  elsif sz[1]=="a"
    t=sz[2].to_i
    b[t]+=tr
    if b[t]>=2
      print stb.chomp
      print " "
      print t
      print " "
      puts sz[0]
    end
  end
end

# 493A

class Foul
  include Comparable
  attr :time

  def initialize(player, time, team)
    @player = player
    @time = time
    @team = team
  end

  def <=>(another)
    time <=> another.time
  end

  def to_s
    [@team, @player, @time].join(' ')
  end
end

names = {h: gets.chomp, a: gets.chomp}
cards = {h: {y: {}, r: {}}, a: {y: {}, r: {}}}
gets.to_i.times do
  time, _team, player, card_colour = gets.chomp.split
  team = _team.to_sym
  unless cards[team][:r].include?(player)
    if card_colour == 'r'
      cards[team][:r][player] = time
    else
      if cards[team][:y].include?(player)
        cards[team][:r][player] = time
      else
        cards[team][:y][player] = time
      end
    end
  end
end

fouls = []
[:h, :a].each { |c| cards[c][:r].each { |k, v| fouls << Foul.new(k, v, names[c]) } }
fouls.sort.each { |foul| puts foul }

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end
    if a[arry[i][1]][arry[i][2]] == nil || a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]==nil) && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if ((a[arry[i][1]]==nil && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (a[arry[i][1]] && a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y') || arry[i][3] == 'r'
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end

    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end

    if a[arry[i][1]][arry[i][2]] == 'y'
      a[arry[i][1]][arry[i][2]] = 'r'
    end

    if a[arry[i][1]][arry[i][2]] == nil
      a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
    end

  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
    if a[arry[i][1]] ==nil
      a.merge!( arry[i][1] => {} )
    end
    a[arry[i][1]].merge!(  arry[i][2] => 'r' )
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end

home = gets.chomp
away = gets.chomp
a = {}
arry = []
n = Integer(gets)
for j in 1..n
  arry[j] = gets.split(" ")
  arry[j].each { |arr| arr.chomp }
end
for i in 1..n
  if (((a[arry[i][1]]==nil || a[arry[i][1]][arry[i][2]]!= 'r') && arry[i][3] == 'r') || ( a[arry[i][1]]  &&  a[arry[i][1]][arry[i][2]] == 'y' && arry[i][3] == 'y'))
    if arry[i][1] == 'a'
      puts "#{away} #{arry[i][2]} #{arry[i][0]}"
    else
      puts "#{home} #{arry[i][2]} #{arry[i][0]}"
    end
  end

  if a[arry[i][1]] ==nil
    a.merge!( arry[i][1] => {} )
  end
  a[arry[i][1]].merge!(  arry[i][2] => arry[i][3] )
end


Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:   Aij = Aji, for all i, j (1 ≤ i, j ≤ n);  Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n);  Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?

The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).

The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.

n = gets.to_i
a = []
n.times do
	a << gets.split(" ").map(&:to_i)
end
b = []
n.times do
	b << []
end
c = []
n.times do
	c << []
end
(0...n).each do |i|
	(0...n).each do |j|
		if i == j
			b[i][j] = a[i][j].to_f
			c[i][j] = 0.0
		elsif i > j
			t = (a[i][j]+a[j][i])/2.0
			b[i][j] = t
			b[j][i] = t
			c[i][j] = a[i][j] - t
			c[j][i] = -c[i][j]
 		end
	end
end

b.each do |v|
	puts v.join(" ")
end
c.each do |v|
	puts v.join(" ")
end


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

n, k = gets.split.map(&:to_i)
xs = gets.split.map(&:to_i)
def get_result k, xs
  diffs=(0..xs.size-2).map do |i| xs[i+1]-xs[i]; end
  if diffs.any?{|d| d>k}
    return -1
  end

  diffs.inject([0]) do |memo,d|
    last = memo.pop
    if(last+d<=k)
      memo<<last+d
    else
      memo<<last
      memo<<d
    end
    memo
  end.length
end
puts get_result k, xs


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
puts (s+[a.pop,s].max)*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
(0..a.length-1).each{|i| if a[i]>s*(2**i)
		s+=a.pop
		break
	end}
puts s*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
puts (s+a.pop)*(2**a.length)

r=lambda{gets.split.map{|i| i.to_i}}
n,m=r.call
a=r.call
b=r.call
f=(0..n-1)
s=f.select{|i| !b.include?(i+1)}.inject(0){|s,i| s+=a[i]}
a=f.select{|i| b.include?(i+1)}.map{|i| a[i]}.sort
a.each{|v| s+=(s>=v) ? s : a.pop*2}
puts s


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

#!/usr/bin/env ruby

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

t = {}

x0, y0, x1, y1 = read_ints
n = read_ints[0]
n.times do
  r, a, b = read_ints
  t[r] = {} if not t.has_key?(r)
  (a..b).each do |i|
    t[r][i] = 1e9
  end
end

q = [[x0, y0]]
t[x0][y0] = 0
while not q.empty?
  x, y = q.shift
  (-1..1).each do |dx|
    (-1..1).each do |dy|
      if dx != 0 || dy != 0
        nx, ny = x + dx, y + dy
        if t.has_key?(nx) && t[nx].has_key?(ny) && t[x][y] + 1 < t[nx][ny]
          t[nx][ny] = t[x][y] + 1
          q.push([nx, ny])
          if nx == x1 && ny == y1
            break(3)
          end
        end
      end
    end
  end
end
if t[x1][y1] == 1e9
  puts -1
else
  puts t[x1][y1]
end


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．
def int(b = 0); gets.to_i + b end
def ints(b = 0); gets.split.map{ |x| x.to_i + b } end
def str; gets.chomp end
OO = (1<<62)-(1<<31)
# ○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．○。．

def solve
  n, q = ints
  a = ints
  n_evens = a.count(&:even?)
  n_odds = a.count(&:odd?)
  s = a.sum
  q.times do
    t, x = ints
    case t
    when 0
      s += n_evens * x
      puts s
      if x.odd?
        n_odds += n_evens
        n_evens = 0
      end
    when 1
      s += n_odds * x
      puts s
      if x.odd?
        n_evens += n_odds
        n_odds = 0
      end
    end
  end
end

t = int
t.times do
  solve
end


Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $$$a$$$ and $$$b$$$. It is known that $$$|b| \leq |a|$$$, that is, the length of $$$b$$$ is at most the length of $$$a$$$.The Cossack considers every substring of length $$$|b|$$$ in string $$$a$$$. Let's call this substring $$$c$$$. He matches the corresponding characters in $$$b$$$ and $$$c$$$, after which he counts the number of positions where the two strings are different. We call this function $$$f(b, c)$$$.For example, let $$$b = 00110$$$, and $$$c = 11000$$$. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings $$$c$$$ such that $$$f(b, c)$$$ is even.For example, let $$$a = 01100010$$$ and $$$b = 00110$$$. $$$a$$$ has four substrings of the length $$$|b|$$$: $$$01100$$$, $$$11000$$$, $$$10001$$$, $$$00010$$$.  $$$f(00110, 01100) = 2$$$; $$$f(00110, 11000) = 4$$$; $$$f(00110, 10001) = 4$$$; $$$f(00110, 00010) = 1$$$. Since in three substrings, $$$f(b, c)$$$ is even, the answer is $$$3$$$.Vus can not find the answer for big strings. That is why he is asking you to help him.

The first line contains a binary string $$$a$$$ ($$$1 \leq |a| \leq 10^6$$$) — the first string. The second line contains a binary string $$$b$$$ ($$$1 \leq |b| \leq |a|$$$) — the second string.

NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: $$$1010$$$, $$$0101$$$, $$$1111$$$, $$$1111$$$.

A = gets.chomp
B = gets.chomp

nx = 0
core = 0
(0...B.size-1).each{ |i|
  nx = (nx + (B[i] == B[i+1] ? 0 : 1)) % 2
  core = (core + (A[i] == B[i] ? 0 : 1)) % 2
}

p (0..(A.size-B.size)).count{ |i|
  right = A[B.size+i-1] == B[-1] ? 0 : 1
  left = A[i] == B[0] ? 0 : 1
  v = (right + core) % 2 == 0
  core = core + left + right + nx
  v
}

A = gets.chomp
B = gets.chomp

nx = 0
core = 0
(0...B.size-1).each{ |i|
  nx = (nx + (B[i] == B[i+1] ? 0 : 1)) % 2
  core = (core + (A[i] == B[i] ? 0 : 1)) % 2
}

p (0..(A.size-B.size)).count{ |i|
  right = A[B.size+i-1] == B[-1] ? 0 : 1
  left = A[i] == B[0] ? 0 : 1
  v = (right + core) % 2 == 0
  core = core + left + right
  v
}


Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.  The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).

Print one integer — the product of all divisors of n modulo 109 + 7.

NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.

MOD = 1000000000 + 7

def f(n, p)
  if p == 0 then
    return 1
  end
  m = f(n, p / 2)
  if p % 2 == 1 then
    return m * m * n % MOD
  else
    return m * m % MOD
  end
end

while s = $stdin.gets() do
  s = $stdin.gets()
  ps = s.split(" ")
  cnt = {}
  ps.each do |p|
    key = p.to_i()
    if cnt[key] then
      cnt[key] = cnt[key] + 1
    else
      cnt[key] = 1
    end
  end

  d = 1
  cnt.each do |key, val|
    d *= val + 1
  end

  ret = 1
  cnt.each do |key, val|
    x = f(key, (val * (val + 1) / 2) % (MOD - 1))
    y = f(x, (d / (val + 1)) % (MOD - 1))
    ret = ret * y % MOD
  end
  puts(ret)
end

def powmod(a, k, m)
  return 1 if k == 0
  t = powmod(a, k / 2, m)
  t = t * t % m
  t = t * a % m if k % 2 == 1
  return t
end

m = gets.chomp.to_i
ps = gets.chomp.split.map(&:to_i)
mod = 10**9 + 7
n = 1

hs = Hash.new(1)
ps.each do |p|
  hs[p] += 1
  n = n * p % mod
end

cnt = 1
hs.each do |_, v|
  cnt = cnt * v % (2 * (mod - 1))
end

r = 1
if cnt % 2 == 1
  hs.each do |k, v|
    r = r * powmod(k, (v - 1) / 2, mod) % mod
  end
end

puts r * powmod(n, cnt / 2, mod) % mod

def powmod(a, k, m)
  return 1 if k == 0
  t = powmod(a, k / 2, m)
  t = t * t % m
  t = t * a % m if k % 2 == 1
  return t
end

m = gets.chomp.to_i
ps = gets.chomp.split.map(&:to_i)
mod = 10**9 + 7
n = 1

hs = Hash.new(1)
ps.each do |p|
  hs[p] += 1
  n = n * p % mod
end

cnt = 1
hs.each do |_, v|
  cnt *= v
end

puts powmod(n, cnt / 2, mod)


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

s = gets.split

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

col = s[2]

dots = []
matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        dots << [x, k]
    end
end

t = {}

dots.size.times do |i|
    dot = dots[i]
    if dot[1]+1 < m then
        if matrix[dot[0]][dot[1]+1] != col then
            if t[matrix[dot[0]][dot[1]+1]] then
                t[matrix[dot[0]][dot[1]+1]] += 1
            else
                t[matrix[dot[0]][dot[1]+1]] = 1
            end
        end
    end
    if dot[1] > 0 then
        if matrix[dot[0]][dot[1]-1] != col then
            if t[matrix[dot[0]][dot[1]-1]] then
                t[matrix[dot[0]][dot[1]-1]] += 1
            else
                t[matrix[dot[0]][dot[1]-1]] = 1
            end
        end
    end
    if dot[0]+1 < n then
        if matrix[dot[0]+1][dot[1]] != col then
            if t[matrix[dot[0]+1][dot[1]]] then
                t[matrix[dot[0]+1][dot[1]]] += 1
            else
                t[matrix[dot[0]+1][dot[1]]] = 1
            end
        end
    end
    if dot[0] > 0 then
        if matrix[dot[0]-1][dot[1]] != col
            if t[matrix[dot[0]-1][dot[1]]] then
                t[matrix[dot[0]-1][dot[1]]] += 1
            else
                t[matrix[dot[0]-1][dot[1]]] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

ns,ms,c = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i
ar = Array.new
for i in 0..n-1
	ar[i] = gets.chomp.split(//)
end

s = Hash.new

for i in 0..n-1
	for j in 0..m-1
		if ar[i][j] == c
			s[ar[i-1][j]] = 1 if i > 0
			s[ar[i+1][j]] = 1 if i < n-1
			s[ar[i][j-1]] = 1 if j > 0
			s[ar[i][j+1]] = 1 if j < m-1
		end
	end
end

s.delete(c)
s.delete(".")
puts s.length

n, m, c = gets.chomp!.split
n = n.to_i
m = m.to_i
ary = []
hash = {}
n.times {ary << gets.chomp!}
n.times do |i|
	m.times do |j|
		if ary[i][j] == c
			hash[ary[i][j]] = 1
			hash[ary[i - 1][j]] = 1 if i - 1 >= 0
			hash[ary[i + 1][j]] = 1 if i + 1 < n
			hash[ary[i][j - 1]] = 1 if j - 1 >= 0
			hash[ary[i][j + 1]] = 1 if j + 1 < m
		end
	end
end
hash.delete c
hash.delete '.'
puts hash.size

def check(y,x)
  return 0<=y && y<$n && 0<=x && x<$m && $room[y][x,1]==$c
end

$n,$m,$c=STDIN.gets.chomp.split
$n=$n.to_i
$m=$m.to_i
$room=[]
$n.times {$room<<STDIN.gets.chomp}
desks={}
$n.times {|i|
  $m.times {|j|
    if $room[i][j,1]==$c || $room[i][j,1]=="." then next end
    if check(i,j-1) || check(i,j+1) || check(i-1,j) || check(i+1,j) then
      desks[$room[i][j,1]]=1
    end
  }
}
print(desks.length,"\n")

n,m,r=gets.split()
r=r[0]
n=n.to_i
m=m.to_i

map=Array.new(n)
for i in 0..n-1
        map[i]=gets.split[0]
end

res=[]
dx=[1,0,-1,0]
for i in 0..n-1
        for j in 0..m-1
                next if map[i][j]!=r
                for k in 0..3
                        nx=i+dx[k]
                        ny=j+dx[k^1]
                        if nx>=0&&nx<n&&ny>=0&&ny<m then
                                res.push(map[nx][ny]) unless map[nx][ny]==r
                        end
                end
        end
end
ans=0

for i in 0..res.length-1
        ok=1
        for j in 0..i-1
                ok=0 if res[i]==res[j]
        end
        next if ok==0||res[i]=="."
        ans+=1
end

p ans

y,x,p = gets.split
y = y.to_i
x = x.to_i

arr = []

y.times do |i|
    line = gets.chomp
    line = line.split(//).join(' ');
    arr[i] = line.split
end
count = 0
exists = []

y.times do |i|
    x.times do |j|
        if arr[i][j] == p
            if  i != 0 && arr[i-1][j] != '.' && arr[i-1][j] != p
                if exists.index(arr[i-1][j]) == nil
                    count = count+1
                    exists << arr[i-1][j]
                end
            end
            if j != 0 && arr[i][j-1] != '.' && arr[i][j-1] != p
                if exists.index(arr[i][j-1]) == nil
                    count = count+1
                    exists << arr[i][j-1]
                end
            end
            if  i != y-1 && arr[i+1][j] != '.' && arr[i+1][j] != p
                if exists.index(arr[i+1][j]) == nil
                    count = count+1
                    exists << arr[i+1][j]
                end
            end
            if j != x-1 && arr[i][j+1] != '.' && arr[i][j+1] != p
                if exists.index(arr[i][j+1]) == nil
                    count = count+1
                    exists << arr[i][j+1]
                end
            end
        end
    end
end
puts count

tmp=gets.chomp.split
n=tmp[0].to_i
m=tmp[1].to_i
c=tmp[2]
memo=Array.new(n)
n.times do |j|
  memo[j]= gets.chomp!.each_char.map{|i| i}
end
ti=0
tj=0
h={}
n.times do |i|
  m.times do |j|
    if memo[i][j]==c
      ti=i
      tj=j
      if ti!=0
        h[memo[ti-1][tj]]=true
      end
      if ti!=n-1
        h[memo[ti+1][tj]]=true
      end
      if tj!=0
        h[memo[ti][tj-1]]=true
      end
      if tj!=m-1
        h[memo[ti][tj+1]]=true
      end
    end
  end
end
h.delete(c)
h.delete(".")
puts h.size

require 'Set'
height,width,color = gets.split
width = width.to_i
height = height.to_i
#p width
#p height
#p color
dh = [-1, 0, 0, 1]
dw = [0, -1, 1, 0]
data = Array.new()
for h in 0...height do
  data[h] = gets
end
ans = Set.new()
ans.add?(color)
for h in 0...height do
  for w in 0...width do
    if data[h][w,1] == color then
      #print h, w
      #puts
      for d in 0...4 do
        nh = h + dh[d]
        nw = w + dw[d]
        if nh >= 0 && nw >= 0 && nh < height && nw < width && data[nh][nw,1] != "." then
          ans.add?(data[nh][nw,1])
        end
      end
    end
  end
end
p ans.size()-1

fst = gets.split
N=fst[0].to_i
M=fst[1].to_i
PresidentsColor=fst[2][0]
matrix = Array.new(N)
N.times do |i|
  line = gets.chomp
  matrix[i] = Array.new(M)
  M.times do |j|
    matrix[i][j] = line[j]
  end
end
deputies = []
matrix.each_index do |i|
  matrix[i].each_with_index do |c,j|
    if c==PresidentsColor
      deputies << matrix[i-1][j] if i!=0
      deputies << matrix[i+1][j] if i!=N-1
      deputies << matrix[i][j-1] if j!=0
      deputies << matrix[i][j+1] if j!=M-1
    end
  end
end
deputies.uniq!
deputies.delete "."[0]
deputies.delete PresidentsColor
puts deputies.size

require 'set'

n, m, p_desk = gets.split
n = n.to_i
m = m.to_i

grid = []
n.times do |index|
	row = gets.chomp.split('')
	grid << row
end

desks = Set.new
0.upto(n - 1) do |x|
	0.upto(m - 1) do |y|
		next if grid[x][y] == ?. or grid[x][y] == p_desk
		desks << grid[x][y] if (x > 0 and grid[x - 1][y] == p_desk) || (y > 0 and grid[x][y - 1] == p_desk) ||
							             (x < n - 1 and grid[x + 1][y] == p_desk) || (y < m - 1 and grid[x][y + 1] == p_desk)
  end
end

puts desks.size

n,m,c = gets.split(/\s+/)
n = n.to_i
m = m.to_i
c = c[0]
a = Array.new(n)
n.times do |i|
  a[i] = gets.strip
end

h = []

0.upto(n-1) do |i|
  0.upto(m-1) do |j|
    next if a[i][j] == ?. or a[i][j] == c
    h << a[i][j] if (i > 0 and a[i-1][j] == c) || (j > 0 and a[i][j-1] == c) ||
                    (i < n-1 and a[i+1][j] == c) || (j < m-1 and a[i][j+1] == c)
  end
end

puts h.uniq.size

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
            break
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

n, m, c = gets.chomp.split
n = n.to_i
m = m.to_i
room = Array.new
n.times { room << gets.chomp }
ret = 0
x = Hash.new
dy = [0, -1, 0, 1]
dx = [-1, 0, 1, 0]
x[c] = true
x["."] = true
(0...n).each do |i|
  (0...m).each do |j|
    if room[i][j] == c
      (0...(dy.length)).each do |k|
        ii, jj = i + dy[k], j + dx[k]
        next unless ii >= 0 && ii < n && jj >= 0 && jj < m
        unless x.has_key? room[ii][jj]
          x[room[ii][jj]] = true
          ret += 1
        end
      end
    end
  end
end

puts ret

s = gets.split

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

col = s[2]

i = []
j = []

matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        i << x
        j << k
    end
end

i = i.uniq
j = j.uniq

t = {}

i.size.times do |x|
    m.times do |y|
        if matrix[i[x]][y] != col then
            if t[matrix[i[x]][y]] then
                t[matrix[i[x]][y]] += 1
            else
                t[matrix[i[x]][y]] = 1
            end
        end
    end
end

j.size.times do |x|
    n.times do |y|
        if matrix[y][j[x]] != col then
            if t[(matrix[y][j[x]])] then
                t[(matrix[y][j[x]])] += 1
            else
                t[(matrix[y][j[x]])] = 1
            end
        end
    end
end

puts t.size-1

s = gets.split

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

col = s[2]

i = []
j = []

matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        i << x
        j << k
    end
end

i = i.uniq
j = j.uniq

t = {}

i.size.times do |x|
    m.times do |y|
        if matrix[i[x]][y] != col then
            if t[matrix[i[x]][y]] then
                t[matrix[i[x]][y]] += 1
            else
                t[matrix[i[x]][y]] = 1
            end
        end
    end
end

j.size.times do |x|
    n.times do |y|
        if matrix[y][j[x]] != col then
            if t[(matrix[y][j[x]])] then
                t[(matrix[y][j[x]])] += 1
            else
                t[(matrix[y][j[x]])] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

s = gets.split

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

col = s[2]

dots = []
matrix = []
n.times do |x|
    matrix << gets.chomp
    k = -1
    while k = matrix[x].index(col, k+1) do
        dots << [x, k]
    end
end

t = {}

dots.size.times do |i|
    dot = dots[i]
    if matrix[dot[0]][dot[1]+1] then
        if matrix[dot[0]][dot[1]+1] != col then
            if t[matrix[dot[0]][dot[1]+1]] then
                t[matrix[dot[0]][dot[1]+1]] += 1
            else
                t[matrix[dot[0]][dot[1]+1]] = 1
            end
        end
    end
    if matrix[dot[0]][dot[1]-1] then
        if matrix[dot[0]][dot[1]-1] != col then
            if t[matrix[dot[0]][dot[1]-1]] then
                t[matrix[dot[0]][dot[1]-1]] += 1
            else
                t[matrix[dot[0]][dot[1]-1]] = 1
            end
        end
    end
    if matrix[dot[0]+1] then
        if matrix[dot[0]+1][dot[1]] != col then
            if t[matrix[dot[0]+1][dot[1]]] then
                t[matrix[dot[0]+1][dot[1]]] += 1
            else
                t[matrix[dot[0]+1][dot[1]]] = 1
            end
        end
    end
    if matrix[dot[0]-1] then
        if matrix[dot[0]-1][dot[1]] != col
            if t[matrix[dot[0]-1][dot[1]]] then
                t[matrix[dot[0]-1][dot[1]]] += 1
            else
                t[matrix[dot[0]-1][dot[1]]] = 1
            end
        end
    end
end

t.delete(".")

puts t.size

n, m, c = gets.chomp!.split
n = n.to_i
m = m.to_i
ary = []
hash = {}
n.times {ary << gets.chomp!}
n.times do |i|
	m.times do |j|
		if ary[i][j] == c
			hash[ary[i][j]] = 1
			hash[ary[i - 1][j]] = 1 if i - 1 >= 0
			hash[ary[i + 1][j]] = 1 if i + 1 < n
			hash[ary[i][j - 1]] = 1 if j - 1 >= 0
			hash[ary[i][j + 1]] = 1 if j + 1 < m
		end
	end
end
puts hash

n,m,r=gets.split()
r=r[0]
n=n.to_i
m=m.to_i

map=Array.new(n)
for i in 0..n-1
        map[i]=gets.split[0]
end

res=[]
dx=[1,0,-1,0]
for i in 0..n-1
        for j in 0..m-1
                next if map[i][j]!=r
                for k in 0..3
                        nx=i+dx[k]
                        ny=j+dx[k^1]
                        if nx>=0&&nx<n&&ny>=0&&ny<m then
                                res.push(map[nx][ny]) unless map[nx][ny]==r
                        end
                end
        end
end
ans=0

for i in 0..res.length-1
        ok=1
        for j in 0..i-1
                ok=0 if res[i]==res[j]
        end
        next if ok==0||res[i]=="."
        p res[i]
        ans+=1
end

p ans

tmp=gets.chomp.split
n=tmp[0].to_i
m=tmp[1].to_i
c=tmp[2]
memo=Array.new(n)
n.times do |j|
  memo[j]= gets.chomp!.each_char.map{|i| i}
end
ti=0
tj=0
h={}
n.times do |i|
  m.times do |j|
    if memo[i][j]==c
      ti=i
      tj=j
      if ti!=0 &&memo[ti-1][tj]!="."
        h[memo[ti-1][tj]]=true
      end
      if ti!=n-1&&memo[ti+1][tj]!="."
        h[memo[ti+1][tj]]=true
      end
      if tj!=0 && memo[ti][tj-1]!="."
        h[memo[ti][tj-1]]=true
      end
    end
  end
end
h.delete(c)
puts h.size

require 'Set'
height,width,color = gets.split
width = width.to_i
height = height.to_i
#p width
#p height
#p color
dh = [-1, 0, 0, 1]
dw = [0, -1, 1, 0]
data = Array.new()
for h in 0...height do
  data[h] = gets
end
ans = Set.new()
ans.add?(color)
for h in 0...height do
  for w in 0...width do
    if data[h][w,1] == color then
      #print h, w
      #puts
      for d in 0...4 do
        nh = h + dh[d]
        nw = w + dw[d]
        if nh >= 0 && nw >= 0 && nh < height && nw < width && data[nh][nw,1] != "." then
          ans.add?(data[h-1][w-1,1])
        end
      end
    end
  end
end
p ans.size()-1

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
            break
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

puts "#{topRow}, #{bottomRow}, #{leftCol}, #{rightCol}"

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input1", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[idx-startingRow] == lastFound
    lastFound = leftCol[idx-startingRow]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[idx-startingRow] == lastFound
    lastFound = rightCol[idx-startingRow]
    found << lastFound
  end
end

puts "#{found.count}"

def extractIndices(office, color)
  startingCol, endingCol, startingRow, endingRow = -1, -1, -1, -1
  office.each_with_index do |row, rIdx|
    if row.include? color
      if startingRow == -1 #we do this just for the first row
        startingCol = row.find_index(color)
        (startingCol..row.length-1).each do |idx|
          if row[idx] != color
            endingCol = idx-1
          end
        end
        if endingCol == -1
          endingCol = row.length-1
        end
      end
      startingRow = rIdx if startingRow == -1
      endingRow = rIdx if rIdx >= endingRow
    end
  end
  return startingCol, endingCol, startingRow, endingRow
end

n, m, color = nil, nil, nil
office = []
# File.open("input2", "r") do |file|
#   n, m, color = file.readline.split(" ")
#   n = n.to_i
#   m = m.to_i
#   n.times do
#     office << file.readline.chomp.split("")
#   end
# end

n, m, color = gets.chomp.split(" ")
n = n.to_i
m = m.to_i
n.times do
  office << gets.chomp.split("")
end

startingCol, endingCol, startingRow, endingRow = extractIndices(office, color)
topRow = startingRow - 1
bottomRow = endingRow + 1
leftCol = startingCol - 1
rightCol = endingCol + 1
found = []

if topRow >= 0
  topRow = office[topRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if topRow[idx-startingCol] == "." or topRow[idx-startingCol] == lastFound
    lastFound = topRow[idx-startingCol]
    found << lastFound
  end
end

if bottomRow < n
  bottomRow = office[bottomRow][startingCol..endingCol]
  lastFound = "."
  (startingCol..endingCol).each do |idx|
    next if bottomRow[idx-startingCol] == "." or bottomRow[idx-startingCol] == lastFound
    lastFound = bottomRow[idx-startingCol]
    found << lastFound
  end
end

if leftCol >= 0
  leftCol = office[startingRow..endingRow].map{|r| r[leftCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if leftCol[idx-startingRow] == "." or leftCol[startingRow] == lastFound
    lastFound = leftCol[idx]
    found << lastFound
  end
end

if rightCol < m
  rightCol = office[startingRow..endingRow].map{|r| r[rightCol]}
  lastFound = "."
  (startingRow..endingRow).each do |idx|
    next if rightCol[idx-startingRow] == "." or rightCol[startingRow] == lastFound
    lastFound = rightCol[idx]
    found << lastFound
  end
end

puts "#{found.length}"


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers. All these integers are distinct, each value from $$$1$$$ to $$$n$$$ appears in the sequence exactly once.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[2, 1, 5, 4, 3]$$$ the answer is $$$4$$$ (you take $$$2$$$ and the sequence becomes $$$[1, 5, 4, 3]$$$, then you take the rightmost element $$$3$$$ and the sequence becomes $$$[1, 5, 4]$$$, then you take $$$4$$$ and the sequence becomes $$$[1, 5]$$$ and then you take $$$5$$$ and the sequence becomes $$$[1]$$$, the obtained increasing sequence is $$$[2, 3, 4, 5]$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. All these integers are pairwise distinct.

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.

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

cur = -1
ans = []

until A.empty?
  l = A[0]
  r = A[-1]

  l = Float::INFINITY if l < cur && cur > 0
  r = Float::INFINITY if r < cur && cur > 0

  if cur < l && l <= r && l != Float::INFINITY
    cur = A.shift
    ans << 'L'
  elsif cur < r && l >= r && r != Float::INFINITY
    cur = A.pop
    ans << 'R'
  else
    break
  end
end

puts ans.size
puts ans.join

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

cur = -1
ans = []

until A.empty?
  l = A[0]
  r = A[-1]

  l = Float::INFINITY if l < cur && cur > 0
  r = Float::INFINITY if r < cur && cur > 0

  if cur < l && l <= r
    cur = A.shift
    ans << 'L'
  elsif cur < r && l >= r
    cur = A.pop
    ans << 'R'
  else
    break
  end
end

puts ans.size
puts ans.join


You are given an array of integers $$$a_1,a_2,\ldots,a_n$$$. Find the maximum possible value of $$$a_ia_ja_ka_la_t$$$ among all five indices $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$5\le n\le 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.In the second test case, choosing $$$a_1,a_2,a_3,a_5,a_6$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.In the third test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.In the fourth test case, choosing $$$a_1,a_2,a_3,a_4,a_6$$$ is a best choice: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.

gets.to_i.times do
  gets
  a = gets.split(" ").map(&:to_i)
  a.sort!

  a[5...a.size-5] = nil
  a.compact!

  best = -999999999999999999999999999999999999999999999999999999999

  (0...a.size).each do |i|
  ((i+1)...a.size).each do |j|
  ((j+1)...a.size).each do |k|
  ((k+1)...a.size).each do |l|
  ((l+1)...a.size).each do |t|
    x = a[i]*a[j]*a[k]*a[l]*a[t]
    best = x if x > best
  end
  end
  end
  end
  end
  p best
end

gets.to_i.times do
  gets
  a = gets.split(" ").map(&:to_i)
  a.sort!

  a[5...a.size-5] = nil
  a.compact!

  best = -9999999999999

  (0...a.size).each do |i|
  ((i+1)...a.size).each do |j|
  ((j+1)...a.size).each do |k|
  ((k+1)...a.size).each do |l|
  ((l+1)...a.size).each do |t|
    x = a[i]*a[j]*a[k]*a[l]*a[t]
    best = x if x > best
  end
  end
  end
  end
  end
  p best
end


To improve the boomerang throwing skills of the animals, Zookeeper has set up an $$$n \times n$$$ grid with some targets, where each row and each column has at most $$$2$$$ targets each. The rows are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns are numbered from $$$1$$$ to $$$n$$$ from left to right.  For each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a $$$90$$$ degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid.   In the above example, $$$n=6$$$ and the black crosses are the targets. The boomerang in column $$$1$$$ (blue arrows) bounces $$$2$$$ times while the boomerang in column $$$3$$$ (red arrows) bounces $$$3$$$ times. The boomerang in column $$$i$$$ hits exactly $$$a_i$$$ targets before flying out of the grid. It is known that $$$a_i \leq 3$$$.However, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.

The first line contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$.  The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ $$$(0 \leq a_i \leq 3)$$$.

If no configuration of targets exist, print $$$-1$$$.  Otherwise, on the first line print a single integer $$$t$$$ $$$(0 \leq t \leq 2n)$$$: the number of targets in your configuration.   Then print $$$t$$$ lines with two spaced integers each per line. Each line should contain two integers $$$r$$$ and $$$c$$$ $$$(1 \leq r,c \leq n)$$$, where $$$r$$$ is the target's row and $$$c$$$ is the target's column. All targets should be different.   Every row and every column in your configuration should have at most two targets each.

NoteFor the first test, the answer configuration is the same as in the picture from the statement. For the second test, the boomerang is not supposed to hit anything, so we can place $$$0$$$ targets. For the third test, the following configuration of targets matches the number of hits, but is not allowed as row $$$3$$$ has $$$4$$$ targets.   It can be shown for this test case that no valid configuration of targets will result in the given number of target hits.

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
target2 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target2 << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target2.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target2[0][1]]
      target2.shift
      target2 << [tate+1,i+1]
      tate -= 1
    elsif target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      target2 << [tate+1,i+1]
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
ans = []
target1 = []
target2 = []
tate = n-1
(n-1).downto(0) do |i|
  if a[i] == 1
    ans << [tate+1,i+1]
    target1 << [tate+1,i+1]
    tate -= 1
  elsif a[i] == 2
    if target1.empty?.!
      ans << [target1[0][0],i+1]
      target2 << [target1[0][0],i+1]
      target1.shift
    else
      puts -1
      exit
    end
  elsif a[i] == 3
    if target2.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target2[0][1]]
      target2.shift
      tate -= 1
    elsif target1.empty?.!
      ans << [tate+1,i+1]
      ans << [tate+1,target1[0][1]]
      target1.shift
      target2 << [tate+1,i+1]
      tate -= 1
    else
      puts -1
      exit
    end
  end
end
puts ans.length
ans.each do |v|
  puts "#{v[0]} #{v[1]}"
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You want to distribute these $$$n$$$ integers into two groups $$$s_1$$$ and $$$s_2$$$ (groups can be empty) so that the following conditions are satisfied:  For each $$$i$$$ $$$(1 \leq i \leq n)$$$, $$$a_i$$$ goes into exactly one group. The value $$$|sum(s_1)| - |sum(s_2)|$$$ is the maximum possible among all such ways to distribute the integers.Here $$$sum(s_1)$$$ denotes the sum of the numbers in the group $$$s_1$$$, and $$$sum(s_2)$$$ denotes the sum of the numbers in the group $$$s_2$$$.Determine the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(-10^9 \leq a_i \leq 10^9)$$$  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single integer  — the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

gets.to_i.times do
    n=gets
    arr=gets.chomp.split.map(&:to_i)
    s1=arr.select{|x| x>0}.sum
    s2=-1*arr.select{|x| x<0}.sum
    puts [s1,s2].max-[s1,s2].min
end


You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

def checks(sizes, selections, array_1, array_2)
  selections = selections.split(' ').map(&:to_i)
  array_1 = array_1.split(' ').map(&:to_i)
  array_2 = array_2.split(' ').map(&:to_i)

  max_1 = array_1.sort.first(selections[0]).max
  max_2 = array_2.sort.last(selections[1]).min

  if max_1 < max_2
    r = 'YES'
  else
    r = 'NO'
  end
  puts r
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
puts arr[k-1]<brr[-m] ? "YES" : "NO"

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    else
        i = lb
    end
end
if (lb-i)>=m
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.split(" ").map!{|val| val=val.to_i}
na=n[0]
nb=n[1]

km = gets.chomp.split(" ").map!{|val| val=val.to_i}
k = km[0]
m = km[1]

Aarray = gets.chomp.split(" ").map! {|val| val=val.to_i}
Barray = gets.chomp.split(" ").map! {|val| val=val.to_i}

puts "YES" if Aarray[k-1] < Barray[nb-m]
puts "NO" unless Aarray[k-1] < Barray[nb-m]

# http://codeforces.com/contest/572/problem/A
x, y = gets.chomp.split.map(&:to_i)
n, m = gets.chomp.split.map(&:to_i)

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

puts a[n - 1] < b[y - m] ? 'YES' : 'NO'

class TaskA
  def initialize
    @nA, @nB = gets.split.map(&:to_i)
    @k, @m = gets.split.map(&:to_i)
    @a = gets.split.map(&:to_i)
    @b = gets.split.map(&:to_i)
  end

  def solve
    if @a[@k-1] < @b[-@m] then
      puts "YES"
    else
      puts "NO"
    end
  end
end

TaskA.new.solve

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)[0..-1]
b = gets.split.map(&:to_i)[0..-1]
if(a[k-1] < b[nb - m])
    puts "YES"
else
    puts "NO"
end

gets
n,m=gets.split.map{|e| e.to_i}
a=gets.split.map{|e| e.to_i}
b=gets.split.map{|e| e.to_i}

puts (a[n-1]<b[b.size-m])?"YES":"NO"

gets
(k, m), a, b = 3.times.map { gets.split(' ').map(&:to_i) }

res = if k <= a.size && m <= b.size && a[k-1] < b[b.size-m]
  "YES"
else
  "NO"
end

puts res

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

q1 = gets.split.map(&:to_i)
q2 = gets.split.map(&:to_i)

puts q1[k-1] < q2[-m] ? "YES" : "NO"

na,nb = gets.split(' ').map(&:to_i)

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

a1 = gets.split(' ').map(&:to_i)
a2 = gets.split(' ').map(&:to_i)

if a1[k-1] < a2[-m]
  puts "YES"
else
   puts "NO"
 end

# coding: utf-8
C = Struct.new(:num, :tag)
na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
nar = gets.split.map(&:to_i) # non-desc order
nbr = gets.split.map(&:to_i) # non-desc order

if nar[k-1] < nbr[nb - m] # 이미 정렬되어있으므로 마지막에서 세번째 숫자만 비교하면 OK
    puts "YES"
else
    puts "NO"
end

na, nb = gets.chomp.split(' ').map(&:to_i)
k, m = gets.chomp.split(' ').map(&:to_i)
as = gets.chomp.split(' ').map(&:to_i)
bs = gets.chomp.split(' ').map(&:to_i)

puts as[k-1] < bs[nb-m] ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
puts a[k - 1] < b[-m] ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
puts bb && b[bb..-1].size >= m ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
c = []
c = b[bb..-1] if bb
puts c.size >= m ? 'YES' : 'NO'

nA,nB = gets.split.map(&:to_i)
k,m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
y = gets.split.map(&:to_i)
puts x[(k-1)] < y[(nB - m)] ? "YES" : "NO"

n1, n2 = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
puts array1[k-1 ] < array2[n2 - m] ? 'YES' : 'NO'

# Ý tưởng:
# Để có khả năng k số trong array a luôn nhỏ hơn m số trong mảng b
# thì ta phải luôn chọn k số nhỏ nhất trong mảng a và m số lớn nhất trong b.
# Nói cách khác, ta phải luôn chọn k số đầu tiên ở a và m số cuối cùng ở b.
# Sau đó ta so sánh số lớn nhất được chọn trong k số ở a và số nhỏ nhất được chọn trong m số ở b.
# Nếu số lớn nhất trong k số đó nhỏ hơn số nhỏ nhất trong m số kia thì kết quả luôn là “YES”, ngược lại là “NO”

size_a, size_b = gets.chomp.split.map(&:to_i)
k, m = gets.chomp.split.map(&:to_i)

array_a = gets.chomp.split.map(&:to_i)
array_b = gets.chomp.split.map(&:to_i)

puts array_a[k - 1] < array_b[-m] ? "YES" : "NO"

def checks(sizes, selections, array_1, array_2)
  selections = selections.split.map(&:to_i)
  array_1 = array_1.split.map(&:to_i)
  array_2 = array_2.split.map(&:to_i)
  puts array_1.sort.first(selections[0]).max < array_2.sort.last(selections[1]).min ? 'YES' : 'NO'
end
checks(gets, gets, gets, gets)

# Array1: Find min elements base on selection after that find max element
# Array2: Find max elements base on selection after that find min element
# Condition value of 2 array if array 1 < array 2 then print 'Yes' otherwise print 'No'

#!/usr/bin/ruby

# def qselect(a, b, k, m)
#   def qloc(a, b)
#     l = a.length
#     return -1 if b <= a[0]
#     return l if b > a[-1]
#     i = 0
#     loop do
#       break -1 if i < 0 or i >= l
#       break i if a[i+1] and b > a[i] and b <= a[i+1]
#       break i if not a[i+1] and b > a[i]
#       i = b > a[i] ? (l + i + 1) / 2 : i / 2
#     end
#   end
#   return false if k > a.length or m > b.length
#   p = qloc(a, b[-m])
#   k <= p + 1
# end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  # puts qselect(a, b, k, m) ? "YES" : "NO"
  puts b[-m] > a[k-1] ? "YES" : "NO"
end

algo

#!/usr/bin/ruby
z,(k,m),A,B=$<.map{|e|e.split.map &:to_i}
puts A.sort[k-1]<B.sort[-m] ? :YES : :NO

def checks(sizes, selections, array_1, array_2)
  selections = selections
  array_1 = array_1.split
  array_2 = array_2.split
  puts 1 < 2 ? 'YES' : 'NO'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    end
end
if (lb-(i+1))>=m
    puts "YES"
else
    puts "NO"
end

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
if k<=la && m<=lb && arr[k-1]<brr[0]
    puts "YES"
else
    puts "NO"
end

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    end
end
if (lb-i)>=m
    puts "YES"
else
    puts "NO"
end

na,nb = gets.split(' ').map(&:to_i)

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

a1 = gets.split(' ').map(&:to_i)
a2 = gets.split(' ').map(&:to_i)

if a1[k-1] < a2[0]
  puts "YES"
else
   puts "NO"
 end

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
puts b[(bb || 0)..-1].size >= m ? 'YES' : 'NO'

skip = gets.chomp.to_i
number_choose = gets.split.map(&:to_i)
arrayA = gets.split.map(&:to_i)
arrayB = gets.split.map(&:to_i)
choosenA = arrayA.last(number_choose[0])
minB = arrayB.first(number_choose[1]).min
puts choosenA.all?{|x| x < minB}  ? 'YES' : 'NO'

skip = gets.chomp
select_numbers = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
count = 0
array = array1 + array2
(array1.length...array.length).each do|index|
  if array[index] <= array[index-1]
    count = index
    break
  end
end

puts ( count > select_numbers.max) ? 'YES' : 'NO'

skip = gets.chomp
select_numbers = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
count = 0
array = array1 + array2
(1...array.length).each do|index|
  if array[index] <= array[index-1]
    count = index
    break
  end
end
puts ( count > select_numbers.max) ? 'YES' : 'NO'

skip = gets.chomp.to_i
number_choosens = gets.split.map(&:to_i)
arrayA = gets.split.map(&:to_i)
arrayB = gets.split.map(&:to_i)
possile_of_a = arrayA.select{|x| x < arrayB.min}
possile_of_b = arrayB.select{|x| x > arrayA.max}
puts (possile_of_a.size >= number_choosens[0] && possile_of_b.size >= number_choosens[1]) ? 'YES' : 'NO'

#!/usr/bin/ruby

def qselect(a, b, k, m)
  def qloc(a, b)
    l = a.length
    i = 0
    loop do
      break -1 if i < 0 or i >= l
      break i if a[i+1] and b > a[i] and b <= a[i+1]
      break i if not a[i+1] and b > a[i]
      i = b >= a[i] ? (l + i + 1) / 2 : (i - 1) / 2
    end
  end

  p = qloc(a, b[0])
  return false if p < 0
  k <= p + 1 && m <= b.length
end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  puts qselect(a, b, k, m) ? "YES" : "NO"
end

algo

#!/usr/bin/ruby

# def qselect(a, b, k, m)
#   def qloc(a, b)
#     l = a.length
#     return -1 if b <= a[0]
#     return l if b > a[-1]
#     i = 0
#     loop do
#       break -1 if i < 0 or i >= l
#       break i if a[i+1] and b > a[i] and b <= a[i+1]
#       break i if not a[i+1] and b > a[i]
#       i = b > a[i] ? (l + i + 1) / 2 : i / 2
#     end
#   end
#   return false if k > a.length or m > b.length
#   p = qloc(a, b[-m])
#   k <= p + 1
# end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  # puts qselect(a, b, k, m) ? "YES" : "NO"
  puts b[-m] > a[-k] ? "YES" : "NO"
end

algo

#!/usr/bin/ruby

def qselect(a, b, k, m)
  def qloc(a, b)
    l = a.length
    return -1 if b <= a[0]
    return l if b > a[-1]
    i = 0
    loop do
      break -1 if i < 0 or i >= l
      break i if a[i+1] and b > a[i] and b <= a[i+1]
      break i if not a[i+1] and b > a[i]
      i = b > a[i] ? (l + i + 1) / 2 : i / 2
    end
  end

  p = qloc(a, b[0])
  return false if p < 0
  k <= p + 1 && m <= b.length
end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  puts qselect(a, b, k, m) ? "YES" : "NO"
end

algo

def checks(sizes, selections, array_1, array_2)
  selections = selections
  puts 1 < 2 ? 'YES' : 'NO'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

def checks(sizes, selections, array_1, array_2)

  puts 'YES'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\leq a, b\leq 100$$$), representing a corresponding test case.

For each test case print the single integer on a separate line — the answer to the problem.

NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.

gets.to_i.times{
    a,b=gets.split
    puts a.to_i*b.to_i
}

t = gets.chomp.to_i
t.times do
	a,b = gets.split()
	p a.to_i*b.to_i
end


Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ — length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!

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

For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.

NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ")
    number_zero = a.count("0")
    number_ichi = n - number_zero
    if number_zero >= number_ichi
        a.delete("1")
        puts a.size
        puts a.join(" ")
    else
        a.delete("0")
        ookisa = a.size
        if ookisa % 2 == 0
            puts a.size
            puts a.join(" ")
        else
            a.pop
            puts a.size
            puts a.join(" ")
        end
    end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  rui_e = [0]
  rui_o = [0]

  a.each_with_index do |x, i|
    if i.even?
      rui_e << rui_e.last + x
      rui_o << rui_o.last
    else
      rui_e << rui_e.last
      rui_o << rui_o.last + x
    end
  end

  idx = -1

  n.times do |i|
    v1 = (rui_e[i] - rui_e[0]) + (rui_o[n] - rui_o[i + 1])
    v2 = (rui_o[i] - rui_o[0]) + (rui_e[n] - rui_e[i + 1])

    if v1 == v2
      idx = i
      break
    end
  end

  if idx != -1
    a.delete_at(idx)
  end

  puts a.size
  puts a.join(' ')
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = a.sum
  t = s / 2
  ans = []
  sum = [0, 0]

  if n <= 2
    puts 1
    puts 0
    next
  end

  until a.empty?
    x = a.shift

    if ans.size.even?
      next if x + sum[0] > t

      sum[0] += x
      ans << x
    else
      next if x + sum[1] > t

      sum[1] += x
      ans << x
    end
  end

  puts ans.size
  puts ans.join(' ')
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ")
    number_zero = a.count("0")
    number_ichi = n - number_zero
    if number_zero >= number_ichi
        a.delete("1")
        puts a.join(" ")
    else
        a.delete("0")
        ookisa = a.size
        if ookisa % 2 == 0
            puts a.join(" ")
        else
            a.pop
            puts a.join(" ")
        end
    end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = a.sum
  t = s / 2
  ans = []
  sum = [0, 0]

  until a.empty?
    x = a.shift

    if ans.size.even?
      next if x + sum[0] > t

      sum[0] += x
      ans << x
    else
      next if x + sum[1] > t

      sum[1] += x
      ans << x
    end
  end

  puts ans.size
  puts ans.join(' ')
end

T = gets.to_i

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

  counter = a.tally
  counter.default = 0

  if counter[0] >= 1
    puts 1
    puts 0
  elsif counter[1] >= 2
    puts 2
    puts "1 1"
  end
end


You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.

NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  x_max = 0
  c = a[0]
  a.each do |v|
    if c > v
      d = c - v
      x = 0
      while d > 0 do
        d /= 2
        x += 1
      end
      x_max = x if x_max < x
    else
      c = v
    end
  end
  puts x_max
end


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
out = [false]*(n+1)

ans = 0
j = 0
n.times do |i|
  if !out[a[i]]
    while b[j] != a[i]
      out[b[j]] = true
      j += 1
      ans += 1
    end
    out[b[j]] = true
    j += 1
  end
end
p ans

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
def inpf() a=gets.chomp.split(" ").map(&:to_f)end
def inps() a=gets.chomp.split(" ")end
def copy(a) Marshal.load(Marshal.dump(a)) end
def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
a = inp
b = inp
table = na(n)
encoded = na(n)
n.times do |i|
  encoded[a[i]-1] = i
end

pl = 0
ans = 0
i = 0
while i < n
  if(table[i] == 1)
    pl -= 1
    i += 1
    next
  end
  if(a[i] != b[i+pl])
    ans += 1
    table[encoded[b[i+pl]-1]] = 1
    pl +=1
  else
    i += 1
  end
end
p ans


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.

For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.

NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.

q = gets.chomp.to_i

for ii in 1..q
  (k, n, a, b) = gets.chomp.split(" ").map {|aaa| aaa.to_i}
  _min = n*b
  k -= 1
  d = a-b
  if _min > k
    print -1
  else
    _max = (k -_min)/d
    print _max > n ? n : _max
  end
  print "\n"
end

q = gets.to_i
(1..q).each do
  res = 0
  read = gets.split(" ").map{|c| c.to_i}
  k = read[0]
  n = read[1]
  a = read[2]
  b = read[3]
  if n * b >= k
    res = -1
  else
    l = 0
    r = n
    while l < r
      m = (l + r + 1)/2
      if m * a + (n - m) * b < k
        l = m
      else
        r = m - 1
      end
    end
    res = l
  end
  puts res
end

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

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

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
q.times do
  bat,turn,a,b=gsmi

  if bat <= turn*b
    puts -1
    next
  end

  b_bat = bat - turn*b
  puts [(b_bat-1)/(a-b),turn,((bat-a).to_f/a).ceil].min
end

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

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

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
q.times do
  bat,turn,a,b=gsmi

  if bat <= turn*b
    puts -1
    next
  end

  b_bat = bat - turn*b
  puts [b_bat/(a-b),turn,((bat-a).to_f/a).ceil].min
end