Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.  There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.  Masculine adjectives end with -lios, and feminine adjectives end with -liala.  Masculine nouns end with -etr, and feminime nouns end with -etra.  Masculine verbs end with -initis, and feminime verbs end with -inites.  Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.  It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.  There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.  A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.  All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.

The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.

If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).

petr
etis atis animatis etis atis amatis
nataliala kataliala vetra feinites

$_ = gets.chomp + ' '
[%w(lios etr initis), %w(liala etra inites)].each do |r|
	r.map!{|_| "\\S*#{_}\\s+"}
	r << "(#{r[0]})*(#{r[1]})(#{r[2]})*";
	if /^(#{r.join('|')})$/
		puts :YES
		exit
	end
end
puts :NO

s = gets.strip
[%w(lios etr initis), %w(liala etra inites)].each do |g|
  r = g.map { |t| "\\S*#{t}(\\s+|$)" }
  r << "(#{r[0]})*#{r[1]}(#{r[2]})*"
  if /^(#{r.join ?|})$/.match s
    puts :YES
    exit
  end
end
puts :NO

def solve(ws)
  ts = ws.map do |w|
    case
    when w.end_with?('lios') then [:adj, :mas]
    when w.end_with?('liala') then [:adj, :fem]
    when w.end_with?('etr') then [:noun, :mas]
    when w.end_with?('etra') then [:noun, :fem]
    when w.end_with?('initis') then [:verb, :mas]
    when w.end_with?('inites') then [:verb, :fem]
    when true then nil
    end
  end
  return false if ts.any?(&:nil?)
  return true if ts.size == 1
  return false unless ts.all?{|x| x[1] == ts[0][1]}
  cb = :adj
  ts.each do |t, _|
    case cb
    when :adj
      case t
      when :noun then cb=:noun
      when :verb then return false
      end
    when :noun,:verb
      case t
      when :adj, :noun then return false
      when :verb then cb=:verb
      end
    end
  end
  return cb == :noun || cb == :verb
end

words = gets.split
puts solve(words) ? 'YES' : 'NO'

class String
  def end_with(s)
    i = self.rindex s
    !i.nil? && self.length - i == s.length
  end
end

$w = [
   %w(lios ma),
   %w(liala fa),
   %w(etr mn),
   %w(etra fn),
   %w(initis mv),
   %w(inites fv),
  ]
def f(str)
  $w.each {|suf, s|
    return s if str.end_with suf
  }
  nil
end

def valid(words)
  return false if words.index nil
  return true if words.length == 1

  return false if words.map{|w|w[0]}.uniq.length > 1
  a = words.map{ |w| w[1] }
  i = 0
  i += 1 while i<a.length && a[i] == 'a'
  return false if i==a.length || a[i] != 'n'
  i += 1
  i += 1 while i<a.length && a[i] == 'v'
  i == a.length
end
words = gets.chomp.split.map{ |s| f s }
puts (valid(words) ? 'YES': 'NO')

w = gets.split
bool = false
if w.size == 1
  w = w[0]
  if w[-3..-1] == 'etr' || w[-4..-1] == 'lios' || w[-4..-1] == 'etra' || w[-5..-1] == 'liala' || w[-6..-1] == 'initis' || w[-6..-1] == 'inites'
    bool = true
  end
else
  if w[0][-4..-1] == 'lios' || w[0][-3..-1] == 'etr'
    while w[0][-4..-1] == 'lios'
      w.shift
      break if w.empty?
    end
    if !w.empty?
      if w[0][-3..-1] == 'etr'
        w.shift
        if !w.empty?
          while w[0][-6..-1] == 'initis'
            w.shift
            break if w.empty?
          end
        end
        bool = true if w.size == 0
      end
    end
  elsif w[0][-5..-1] == 'liala' || w[0][-4..-1] == 'etra'
    while w[0][-5..-1] == 'liala'
      w.shift
      break if w.empty?
    end
    if !w.empty?
      if w[0][-4..-1] == 'etra'
        w.shift
        if !w.empty?
          while w[0][-6..-1] == 'inites'
            w.shift
            break if w.empty?
          end
        end
        bool = true if w.size == 0
      end
    end
  end
end
if bool
  puts "YES"
else
  puts "NO"
end

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

class GrammarError < StandardError; end

class String
  def gender
    x, _ = categorize
    x
  end

  def speech
    _, x = categorize
    x
  end

  def categorize
    if end_with? 'lios'
      [:masculine, :adj]
    elsif end_with? 'liala'
      [:feminine, :adj]
    elsif end_with? 'etr'
      [:masculine, :noun]
    elsif end_with? 'etra'
      [:feminine, :noun]
    elsif end_with? 'initis'
      [:masculine, :verb]
    elsif end_with? 'inites'
      [:feminine, :verb]
    else
      raise GrammarError
    end
  end

  def correct_sentence?
    cs = split(/\s+/).map(&:categorize)
    gs = cs.map { |c| c[0] }
    if gs.find { |g| g != gs[0] }
      return false
    end

    if cs.size == 1
      return true
    end
    ss = cs.map { |c| c[1] }
    sss = ss.drop_while { |c| c == :adj }
    if sss[0] != :noun
      return false
    end
    return sss.drop(1).all? { |c| c == :verb }
  rescue
    false
  end
end

puts (gets.correct_sentence? ? 'YES' : 'NO')

def get_word(w)
  ret = Hash.new
  ret[:gender] = nil
  ret[:type] = nil
  ret[:valid] =  false
  if w.end_with?("lios") then
    ret[:gender] = :m
    ret[:type] = :adjective
    ret[:valid] = true
  elsif w.end_with?("liala") then
    ret[:gender] = :f
    ret[:type] = :adjective
    ret[:valid] = true
  elsif w.end_with?("etr") then
    ret[:gender] = :m
    ret[:type] = :noun
    ret[:valid] = true
  elsif w.end_with?("etra") then
    ret[:gender] = :f
    ret[:type] = :noun
    ret[:valid] = true
  elsif w.end_with?("initis") then
    ret[:gender] = :m
    ret[:type] = :verb
    ret[:valid] = true
  elsif w.end_with?("inites") then
    ret[:gender] = :f
    ret[:type] = :verb
    ret[:valid] = true
  end

  ret
end

str = $stdin.readline.split(' ')

words = Array.new
str.each do |w|
  words.push get_word(w)
end

gender = words[0][:gender]
words.each do |w|
  if not w[:gender] == gender then
    puts "NO"
    exit
  end

  if not w[:valid] then
    puts "NO"
    exit
  end
end

if words.count == 1 then
  puts "YES"
  exit
end

i = 0
while words[i][:type] == :adjective
  i += 1
  if i >= words.count then
    puts "NO"
    exit
  end
end

unless words[i][:type] == :noun
  puts "NO"
  exit
end
i += 1
if i >= words.count then
  puts "YES"
  exit
end

while i < words.count
  if words[i][:type] != :verb then
    puts "NO"
    exit
  end
  i += 1
end

puts "YES"

def g(s)
  case s
  when /lios$/
    return 1, 0
  when /liala$/
    return 1, 1
  when /etr$/
    return 2, 0
  when /etra$/
    return 2, 1
  when /initis$/
    return 3, 0
  when /inites$/
    return 3, 1
  else
    return -1, -1
  end
end

def v(words)
  if words.size == 0
    return false
  end
  if words.size == 1
    return words[0][0] >= 0
  end
  last_type = -1
  c = 0
  words.each { |w|
    return false if w[0] < 0
    return false if w[1] != words[0][1]
    c += 1 if w[0] == 2
    return false if w[0] < last_type
    last_type = w[0]
  }
  return c == 1
end

words = gets.split
if v(words.map { |s| g(s) })
  puts 'YES'
else
  puts 'NO'
end

def g(s)
  case s
  when /lios$/
    return 1, 0
  when /liala$/
    return 1, 1
  when /etr$/
    return 2, 0
  when /etra$/
    return 2, 1
  when /initis$/
    return 3, 0
  when /inites$/
    return 3, 1
  else
    return -1, -1
  end
end

def v(words)
  return false if words.size==0
  return words[0][0] >= 0 if words.size==1
  l=-1
  c=0
  words.each { |w|
    return false if w[0]<0
    return false if w[1]!=words[0][1]
    c+=1 if w[0]==2
    return false if w[0]<l
    l=w[0]
  }
  return c == 1
end

words = gets.split
if v(words.map {|s| g(s) })
  puts 'YES'
else
  puts 'NO'
end

def get_info(s)
  case s
  when /lios$/
    return 1, 0
  when /liala$/
    return 1, 1
  when /etr$/
    return 2, 0
  when /etra$/
    return 2, 1
  when /initis$/
    return 3, 0
  when /inites$/
    return 3, 1
  else
    return -1, -1
  end
end

def verify(words)
  if words.size == 0
    return false
  end
  if words.size == 1
    return words[0][0] >= 0
  end
  last_type = -1
  count_noun = 0
  words.each { |word|
    # Must be valid word
    if word[0] < 0
      return false
    end
    # Must have same gender
    if word[1] != words[0][1]
      return false
    end
    # Must be increasing in type
    if word[0] == 2
      count_noun += 1
    end
    if word[0] < last_type
      return false
    end
    last_type = word[0]
  }
  return count_noun == 1
end

[*$<].each { |line|
  words = line.split
  if verify(words.map { |s| get_info(s) })
    puts 'YES'
  else
    puts 'NO'
  end
}

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1...words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    pos += 1
  end

  for i in pos...words.size
    unless (gender == :male and words[i] =~ /initis$/) or (gender == :female and words[i] =~ /inites$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    i += 1
  end

  for i in pos..words.size
    if (gender == :male and words[i] =~ /inites$/) or (gender == :female and words[i] =~ /initis$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    i += 1
  end

  for i in pos..words.size
    unless words[i] =~ /(initis|inites)$/
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    pos += 1
  end

  for i in pos..words.size
    if (gender == :male and words[i] =~ /inites$/) or (gender == :female and words[i] =~ /initis$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    i += 1
  end

  for i in pos..words.size
    if (gender == :male and words[i] =~ /inites$/) or (gender == :female and words[i] =~ /initis$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

$_ = gets.chomp + ' '
[%w(lios etr initis), %w(liala etra inites)].each do |r|
	r.map!{|_| "\\S*#{_}\\s+"}
	r << "(#{r[0]})*(#{r[1]})(#{r[2]})*";
	if /^(#{r.join('|')})$/
		puts $&
		puts :YES
		exit
	end
end
puts :NO

$_ = gets.chomp + ' '
[%w(lios etr initis), %w(liala etra inites)].each do |r|
	r.map!{|_| ".*#{_}\s+"}
	r << "(#{r[0]})*(#{r[1]})(#{r[2]})*";
	if /^#{r.join('|')}$/
		puts :YES
		exit
	end
end
puts :NO

s = gets.strip
[%w(lios etr initis), %w(liala etra inites)].each do |g|
  r = g.map { |t| "\\S*#{t}(\\s+|$)" }
  r << "(#{r[0]})*#{r[1]}(#{r[2]})*"
  if /^#{r.join ?|}$/.match s
    puts :YES
    exit
  end
end
puts :NO

def solve(ws)
  ts = ws.map do |w|
    return [:adj, :mas] if w.end_with?('lios')
    return [:adj, :fem] if w.end_with?('liala')
    return [:noun, :mas] if w.end_with?('etr')
    return [:noun, :fem] if w.end_with?('etra')
    return [:verb, :mas] if w.end_with?('initis')
    return [:verb, :fem] if w.end_with?('inites')
    return nil
  end
  return false if ts.any?(&:nil)
  return true if ts.size == 1
  return false unless ts.all?{|x| x[1] == ts[0][1]}
  cb = :adj
  ts.each do |t, _|
    case cb
    when :adj
      case t
      when :noun then cb=:noun
      when :verb then return false
      end
    when :noun,:verb
      case t
      when :adj, :noun then return false
      when :verb then cb=:verb
      end
    end
  end
  return cb == :noun || cb == :verb
end

words = gets.split
puts solve(words) ? 'YES' : 'NO'

w = gets.split
bool = false
if w.size == 1
  w = w[0]
  if w[-3..-1] == 'etr' || w[-4..-1] == 'lios' || w[-4..-1] == 'etra' || w[-5..-1] == 'liala' || w[-6..-1] == 'initis' || w[-6..-1] == 'inites'
    bool = true
  end
else
  if w[0][-4..-1] == 'lios' || w[0][-3..-1] == 'etr'
    while w[0][-4..-1] == 'lios'
      w.shift
      break if w.empty?
    end
    if !w.empty?
    w.shift if w[0][-3..-1] == 'etr'
    if !w.empty?
    while w[0][-6..-1] == 'initis'
      w.shift
      break if w.empty?
    end
    end
    bool = true if w.size == 0
    end
  elsif w[0][-5..-1] == 'liala' || w[0][-4..-1] == 'etra'
    while w[0][-5..-1] == 'liala'
      w.shift
      break if !w.empty?
    end
    if !w.empty?
    w.shift if w[0][-4..-1] == 'etra'
    if !w.empty?
    while w[0][-6..-1] == 'inites'
      w.shift
      break if w.empty?
    end
    bool = true if w.size == 0
    end
    end
  end
end
if bool
  puts "YES"
else
  puts "NO"
end

def get_info(s)
  case s
  when /lios$/
    return 1, 0
  when /liala$/
    return 1, 1
  when /etr$/
    return 2, 0
  when /etra$/
    return 2, 1
  when /initis$/
    return 3, 0
  when /inites$/
    return 3, 1
  else
    return -1, -1
  end
end

def verify(words)
  if words.size == 0
    return false
  end
  last_type = -1
  count_noun = 0
  words.each { |word|
    # Must be valid word
    if word[0] < 0
      return false
    end
    # Must have same gender
    if word[1] != words[0][1]
      return false
    end
    # Must be increasing in type
    if word[0] == 2
      count_noun += 1
    end
    if word[0] < last_type
      return false
    end
    last_type = word[0]
  }
  return count_noun == 1
end

[*$<].each { |line|
  words = line.split
  if verify(words.map { |s| get_info(s) })
    puts 'YES'
  else
    puts 'NO'
  end
}

def get_info(s)
  case s
  when /lios$/
    return 1, 0
  when /liala$/
    return 1, 1
  when /etr$/
    return 2, 0
  when /etra$/
    return 2, 1
  when /initis$/
    return 3, 0
  when /inites$/
    return 3, 1
  else
    return -1, -1
  end
end

def verify(words)
  if words.size == 0
    return false
  end
  if words.size == 1
    return true
  end
  last_type = -1
  count_noun = 0
  words.each { |word|
    # Must be valid word
    if word[0] < 0
      return false
    end
    # Must have same gender
    if word[1] != words[0][1]
      return false
    end
    # Must be increasing in type
    if word[0] == 2
      count_noun += 1
    end
    if word[0] < last_type
      return false
    end
    last_type = word[0]
  }
  return count_noun == 1
end

[*$<].each { |line|
  words = line.split
  if verify(words.map { |s| get_info(s) })
    puts 'YES'
  else
    puts 'NO'
  end
}

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    pos += 1
  end

  for i in pos..words.size
    unless words[i] =~ /(initis|inites)$/
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    i += 1
  end

  for i in pos..words.size
    if (gender == :male and words[i] =~ /inites$/) or (gender == :female and words[i] =~ /initis$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1...words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    pos += 1
  end

  for i in pos...words.size
    if words[i] =~ /(initis|inites)$/
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    i += 1
  end

  for i in pos..words.size
    if words[i] =~ /(initis|inites)$/
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end

words = gets.split

if words.size == 1 and words.first =~ /(etr|etra|lios|liala|inites|initis)$/
  puts "YES"
elsif words.size == 1
  puts "NO"
else
  first = words.first
  if first =~ /(lios|etr)$/
    gender = :male
  elsif first =~ /(liala|etra)$/
    gender = :female
  else
    puts "NO"
    Process.exit
  end

  for i in 1..words.size
    if (gender == :male and words[i] =~ /(liala|etra|inites)$/) or (gender == :female and words[i] =~ /(lios|etr|initis)$/)
      puts "NO"
      Process.exit
    end
  end

  pos = 1
  type = (first =~ /(etr|etra)$/) ? :noun : :adj

  if type == :adj
    pos += 1 while words[pos] =~ /(lios|liala)$/
    unless words[pos] =~ /(etr|etra)$/
      puts "NO"
      Process.exit
    end
    pos += 1
  end

  for i in pos..words.size
    unless (gender == :male and words[i] =~ /initis$/) or (gender == :female and words[i] =~ /inites$/)
      puts "NO"
      Process.exit
    end
  end

  puts "YES"
end


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

gets.to_i.times do
  hp_c, atk_c = gets.split.map(&:to_i)
  hp_m, atk_m = gets.split.map(&:to_i)
  k, atk_up, hp_up = gets.split.map(&:to_i)

  solution_found = false
  (0..k).each do |ak|
    hpk = k - ak
    hp = hp_c + hpk * hp_up
    atk = atk_c + ak * atk_up
    dmg = (((hp_m + atk - 1) / atk) - 1) * atk_m
    if dmg < hp
      solution_found = true
      break
    end
  end

  puts(solution_found ? "YES" : "NO")
end

gets.to_i.times do
  hp_c, atk_c = gets.split.map(&:to_i)
  hp_m, atk_m = gets.split.map(&:to_i)
  k, atk_up, hp_up = gets.split.map(&:to_i)

  solution_found = false
  (0..k).each do |ak|
    hpk = k - ak
    hp = hp_c + hpk * hp_up
    atk = atk_c + ak * atk_up
    dmg = (hp_m / atk) * atk_m
    if dmg < hp
      solution_found = true
      break
    end
  end

  puts(solution_found ? "YES" : "NO")
end


Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

#我现在的想法是：把相连的点放在一个集合里，然后统计相连的点至少要多少条边，
#如果总边数不够，就打印no，如果总边数够就打印yes！
#今天算是知道了dsu的意思！
#dsu==disjont set！?
nm=gets.chomp.split.map{|x| x.to_i }
n=nm[0]
m=nm[1]
$parent=Array.new(1+n)
$rank=Array.new(1+n)
$size=Array.new(1+n,1)
for i in 0..n
	$parent[i]=i
	$rank[i]=0
end
def find(a)
	while $parent[a]!=a
		a=$parent[a]
	end
	return a
end
def union(a,b)
	ra=find(a)
	rb=find(b)
	if ra==rb
		return
	end
	if $rank[ra]<$rank[rb]
		$parent[ra]=rb
		$size[rb]+=$size[ra];
		$size[ra]=0;
	elsif $rank[ra]>$rank[rb]
		$parent[rb]=ra
		$size[ra]+=$size[rb];
		$size[rb]=0;
	else
		$parent[rb]=ra
		$rank[ra]+=1
		$size[ra]+=$size[rb];
		$size[rb]=0;
	end
end
m.times do
	ab=gets.chomp.split.map{|x| x.to_i }
	union(ab[0],ab[1])
end
see=Array.new(1+n,0)
def all_connect(n)
	n*(n-1)/2
end
#puts $size.join(" ")
total_edge=0
#puts $parent.join(" ")
for i in 1..n
	total_edge+=all_connect($size[i])
	#puts all_connect($size[i])
end
#puts total_edge
#puts m
if total_edge==m
	puts "YES"
else
	puts "NO"
end

require 'set'
n, m = gets.split.map(&:to_i)

#friends = Set.new # friends with... er... friends. For .delete() only
friendships = Hash.new do |hash, key|
	hash[key] = []
end # id => [f1, f2, ...]
#friends[A][B], A<B == (A is friend to B)

m.times do
	f1, f2 = gets.split.map(&:to_i)
	friendships[f1] << f2
	friendships[f2] << f1
end
#p friends
#p m

while friendships.size>0
	#p friendships
	f_id, friends = friendships.first
	friendships.delete(f_id)
	next if friends.size == 0
	friends_to_check = friends
	friends_checked = Set.new([f_id])
	friends_count = friends.length
	#p "#> #{f_id} #{friends_count} #{friends}"
	until friends_to_check.empty?
		f = friends_to_check.pop
		friends = friendships[f]
		friendships.delete(f)
		next if friends_checked.include? f
		#p ">>> #{f} #{friends}"
		if friends.size != friends_count
			#OOPS.
			puts "NO"
			exit
		end
		friends.each do |f_new|
			next if friends_checked.include? f_new
			friends_to_check << f_new
		end
		friends_checked << f
	end
	#p "#: #{friends_checked}; #{friends_count}"
	if friends_checked.size!=friends_count+1
		#OOPS!
		puts "NO"
		exit
	end
end
puts "YES"

#1. Accomodate Inputs & Initialize
n = gets(" ").to_i
m = gets.chomp.to_i

relations = Array.new(n+1){Array.new()}
(1..m).each do |i|
  a = gets(" ").to_i
  b = gets.chomp.to_i
  relations[a].push(b)
  relations[b].push(a)
end

amigos = Array.new(n+1, false)
back = Array.new()
stack = Array.new()

#2. Build equivalent classes
(1..n).each do |i|
  next if relations[i].empty?

  back.each{ |n| amigos[n] = false }
  back.clear()
  stack.clear()

  amigos[i] = true
  stack.push(i)
  back.push(i)
  ne = 1
  nr = 0

  until (stack.empty?)
    head = stack.pop()
    relations[head].each do |e|
      if !amigos[e]
        ne += 1
        stack.push(e)
        back.push(e)
        amigos[e] = true
      end
    end
    nr += relations[head].length()
    relations[head].clear()
  end

  if (ne-1)*ne != nr
    puts "NO"
    exit
  end
end

puts "YES"

#我现在的想法是：把相连的点放在一个集合里，然后统计相连的点至少要多少条边，
#如果总边数不够，就打印no，如果总边数够就打印yes！
#今天算是知道了dsu的意思！
#dsu==disjont set！?
nm=gets.chomp.split.map{|x| x.to_i }
n=nm[0]
m=nm[1]
$parent=Array.new(1+n)
$rank=Array.new(1+n)
$size=Array.new(1+n,0)
$see=Array.new(1+n,0)
for i in 0..n
	$parent[i]=i
	$rank[i]=0
end
def find(a)
	if $parent[a]!=a
		$parent[a]=find($parent[a])
	end
	return $parent[a]
end
def union(a,b)
	ra=find(a)
	rb=find(b)
	if ra==rb
		return
	end
	if $rank[ra]<$rank[rb]
		$parent[ra]=rb
	elsif $rank[ra]>$rank[rb]
		$parent[rb]=ra
	else
		$parent[rb]=ra
		$rank[ra]+=1
	end
	if $see[a]==0 && $see[b]==0
		$size[find(a)]+=2
		$see[a]=1
		$see[b]=1
	elsif $see[a]==1 && $see[b]==0
		$size[find(a)]+=1
		$see[b]=1
	elsif $see[a]==0 && $see[b]==1
		$size[find(b)]+=1
		$see[a]=1
	end
end
m.times do
	ab=gets.chomp.split.map{|x| x.to_i }
	union(ab[0],ab[1])
end
see=Array.new(1+n,0)
def all_connect(n)
	n*(n-1)/2
end
total_edge=0
for i in 1..n
	total_edge+=all_connect($size[i])
end
if total_edge==m
	puts "YES"
else
	puts "NO"
end

#1. Accomodate inputs & Initialize
n = gets(" ").to_i
m = gets.chomp.to_i

relations = Array.new(n+1){Array.new()}
(1..m).each do |i|
  a = gets(" ").to_i
  b = gets.chomp.to_i
  relations[a].push(b)
end

amigos = Array.new(n+1, 0)
stack = Array.new()

#2. Build equivalent classes
(1..n).each do |i|
  next if relations[i].empty?

  ne = 1
  nr = 0
  amigos.fill(false)
  stack.clear()

  amigos[i] = true
  stack.push(i)

  while (!stack.empty?)
    head = stack.pop()
    relations[head].each do |e|
      if !amigos[e]
        ne += 1
        stack.push(e)
        amigos[e] = true
      end
    end
    nr += relations[head].length()
    relations[head].clear()
  end

  if ((ne-1)*ne)/2 != nr
    puts "NO"
    exit
  end
end

puts "YES"


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.

NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).

n = gets(' ').to_i
m = gets.to_i
s = Array.new(n) do
    gets.split
end
a = gets(' ').to_i
b = gets.to_i

l = []

if a<=n && b<=m
    for i in 0..(n-a)
    for j in 0..(m-b)
        l << s[i,a].map{|k|k[j,b]}.flatten.count('1')
    end
    end
end

if a<=m && b<=n
    for i in 0..(n-b)
    for j in 0..(m-a)
        l << s[i,b].map{|k|k[j,a]}.flatten.count('1')
    end
    end
end

p l.min

def solve(a,b)
    ans=999999999
    $w.times{|x|
        $h.times{|y|
            if x+a-1<$w && y+b-1<$h then
                tans=0
                a.times{|i|
                    b.times{|j|
                        if $map[y+j][x+i]==1 then
                            tans+=1
                        end
                    }
                }
                ans=[ans,tans].min
            end
        }
    }
    return ans
end
$h,$w=gets.split.map(&:to_i)
$map=[]
$h.times{ $map.push(gets.split.map(&:to_i)) }
a,b=gets.split.map(&:to_i)
puts [solve(a,b),solve(b,a)].min

def anal(memo,n,m,a,b)
	min=n*m
	1.upto(n-a+1){|i|1.upto(m-b+1){|j|
		temp=memo[i-1][j-1]+memo[i+a-1][j+b-1]-memo[i+a-1][j-1]-memo[i-1][j+b-1]
		min=temp if temp<min
	}}
	min
end
n,m=gets.split.map(&:to_i)
input=(1..n).map{gets.split.map(&:to_i)}
a,b=gets.split.map(&:to_i)
memo=Array.new(n+1){Array.new(m+1,0)}
1.upto(n){|i|sum=0
1.upto(m){|j|
	sum+=input[i-1][j-1]
	memo[i][j]=memo[i-1][j]+sum
}}
min=anal(memo,n,m,a,b)
ans=[min,anal(memo.transpose,m,n,a,b)].min
p ans

n = gets(' ').to_i
m = gets.to_i
s = Array.new(n) do
    gets.split
end
a = gets(' ').to_i
b = gets.to_i

l = []

if a<=m && b<=n
    for i in 0..(n-a)
    for j in 0..(m-b)
        l << s[i,a].map{|k|k[j,b]}.flatten.count('1')
    end
    end
end

if a<=m && b<=n
    for i in 0..(n-b)
    for j in 0..(m-a)
        l << s[i,b].map{|k|k[j,a]}.flatten.count('1')
    end
    end
end

p l.min


Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).  Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

#!/usr/bin/ruby

n, m = $stdin.readline.split.map(&:to_i)
map = []
n.times {
  s = $stdin.readline
  gnome = 0
  sweaty = 0
  for pos in 0..s.length - 1
    c = s[pos].chr
    case c
      when 'G'
        gnome = pos
      when 'S'
        sweaty = pos
    end
  end
  if gnome > sweaty
    puts -1
    exit
  end
  map.push(sweaty-gnome)
}

map.sort!

ans = 1

map.each_index{ |i|
  if i != 0
    if map[i-1] != map[i]
      ans += 1
    end
  end
}

puts "#{ans}"

gets
d = []
while s = gets do
  g = s.index 'G'
  f = s.index 'S'
  if g > f
    p -1
    exit
  end
  d << f - g
end
p d.uniq.length

gets
d = []
while s = gets do
  g = s.index 'G'
  f = s.index 'S'
  if !g or !f or g > f
    p -1
    exit
  end
  d << f - g
end
p d.uniq.length

n, m = gets.split(" ").map &:to_i
distances = []
n.times do
  s = gets
  gnome = s.index 'G'
  flower = s.index 'S'
  if !gnome or !flower or gnome > flower
    p -1
    exit
  end
  distances << flower - gnome
end
p distances.uniq.length

n,m=gets.split.map(&:to_i)
b=[]
n.times{
	a=gets.chomp
	b<<a.index('S')-a.index('G')
}
b.sort!.uniq!
if b[0]<0
	puts -1
else
	puts b.size
end

n, m = gets.split.map &:to_i
map = Array.new(n)
all = []
f = Array.new(m) { 0 }
last = Array.new(m) { Array.new }
f[0] = 1
n.times do |i|
    map[i] = gets.chomp.split(//)
    g = -1; s = -1
    map[i].each_with_index do |x, i|
        g = i if x == 'G'
        s = i if x == 'S'
    end
    if s == -1 || g == -1 || g > s
        puts -1
        exit
    end
    all << s - g
end
puts all.uniq.size

n, m = gets.split.collect{|i| i.to_i}
ans = Array.new(n)
n.times do |i|
    s = gets.chomp
    d = s.index("G")
    c = s.index("S")
    if d > c
        puts -1
        exit
    end
    ans[i] = c-d
end
puts ans.uniq.size

def check_min_distance (board)
	distance = []
	board.each do |row|
		dwarf = 0
		candy = 0
		row.each_with_index do |c, index|
			if c == "G"
				dwarf = index
			elsif c == "S"
				candy = index
			end
		end
		if dwarf < candy
			distance << (candy - dwarf)
		else
			return -1
		end
	end

	return (distance.uniq).length

end

board = []
row = (((gets()).split(" ")).shift).to_i - 1

for i in 0..row
	ary = []
	(gets()).each_char{ |c| ary << c }
	ary.pop
	board << ary
end

puts check_min_distance(board)

n, m = gets.split.map &:to_i
map = Array.new(n)
all = []
f = [true]
n.times do |i|
    map[i] = gets.chomp.split(//)
    g = -1; s = -1
    map[i].each_with_index do |x, i|
        g = i if x == 'G'
        s = i if x == 'S'
    end
    if s == -1 || g == -1 || g > s
        puts -1
        exit
    end
    all << s - g
end
ans = 0
all = all.uniq.sort
all.each do |x|
    if !f[x]
        ans += 1
        m.downto(x) do |i|
            f[i] = true if f[i - x]
        end
    end
end
puts ans

n, m = gets.split.collect{|i| i.to_i}
ans = 0
n.times do
    s = gets.chomp
    d = s.index("G")
    c = s.index("S")
    if d > c
        ans = -1
        break
    end
    ans = c-d-1 if ans < c-d-1
end
puts ans

def check_min_distance (board, n)
    min = -1
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if min == -1
                min = candy - dwarf
            elsif (candy - dwarf) < min
                min = candy - dwarf
            end
        elsif dwarf != n
            if (n - dwarf) < min
                min = n - dwarf
            end
        elsif dwarf == n
            return -1
        end
    end

    return min
end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1
n = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance(board, n)

def check_min_distance (board, n)
    min = -1
    far_goal = 0
    over_dwarf = 0
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if far_goal < (candy-1 - dwarf)
                far_goal = (candy-1 - dwarf)
            end
        elsif dwarf != n and (candy < dwarf)
            if over_dwarf < dwarf
                over_dwarf = dwarf
            end
        elsif dwarf == n
            return -1
        end
    end

    if (over_dwarf != 0)
        return (n - over_dwarf)
    else
        return far_goal
    end
end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1
n = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance(board, n)

def check_min_distance (board)
    min = -1
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if min == -1
                min = candy - dwarf
            elsif (candy - dwarf) < min
                min = candy - dwarf
            end
        end
    end

    return min
end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance board

def check_min_distance (board, n)
    min = -1
    far_goal = 0
    over_dwarf = 0
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if far_goal < (candy-1 - dwarf)
                far_goal = (candy-1 - dwarf)
            elsif dwarf == candy-1
                return -1
            end
        elsif dwarf != n and (candy < dwarf)
            if over_dwarf < dwarf
                over_dwarf = dwarf
            end
        elsif dwarf == n
            return -1
        end
    end

    if (over_dwarf != 0)
        return (n - over_dwarf)
    else
        return far_goal
    end
end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1
n = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance(board, n)

def check_min_distance (board, n)
    min = -1
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if min == -1
                min = candy - dwarf
            elsif (candy - dwarf) < min
                min = candy - dwarf
            end
        elsif dwarf != n
            if (n - dwarf) < min
                min = n - dwarf
            end
        end
    end

    return min
end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1
n = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance(board, n)

def check_min_distance (board, n)
    min = -1
    near_goal = n
    over_dwarf = 0
    board.each do |row|
        dwarf = 0
        candy = 0
        row.each_with_index do |c, index|
            if c == "G"
                dwarf = index
            elsif c == "S"
                candy = index
            end
        end
        if dwarf < candy
            if (candy - dwarf) < near_goal
                near_goal = (candy - dwarf)
            end
        elsif dwarf != n and (candy < dwarf)
            if over_dwarf < dwarf
                over_dwarf = dwarf
            end
        elsif dwarf == n
            return -1
        end
    end

    if (over_dwarf != 0) and (over_dwarf < near_goal)
        return (n - over_dwarf)
    end
    return near_goal

end

board = []
first_line = (gets()).split(" ")
row = (first_line.shift).to_i - 1
n = (first_line.shift).to_i - 1

for i in 0..row
    ary = []
    (gets()).each_char{ |c| ary << c }
    ary.pop
    board << ary
end

puts check_min_distance(board, n)


Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.

Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.

NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.In the third sample, the optimal solution is {3, 5} and {7}.

_,n=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).reverse
r=0
n.times.map{|i|r=[r,(a[i]||0)+(a[2*n-1-i]||0)].max}
p r

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

h, k = gis
s = gis

x = s.pop k

p x.zip(s.reverse + [0] * (k - s.size)).map{|x,y| x+y}.max

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

# b.rb

def main()
    n, k = gets.chomp().split(" ").map{|si| next si.to_i() }
    s = gets.chomp().split(" ").map{|si| next si.to_i() }

    m = s[-1]
    t = n - k
    t.times do |tt|
        mm = s[tt] + s[2 * t - 1 - tt]
        m = mm if m < mm
    end
    puts m
end

if __FILE__ == $0 then
    main()
end

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

puts (0...(n - k)).to_a.inject(ss[-1]) { |m, i| [m, ss[i] + ss[2 * (n - k) - i - 1]].max }

def main()
	a = gets.split(" ").map{|i| i.to_i}
	n = a[0]
	k = a[1]
	s = gets.split(" ").map{|i| i.to_i}
	s = [-1]+s
	if n <= k
		puts s[n]
	else
		sol = s[n]
		for i in 0...n-k
			x = s[n-k-i]+s[n-k+1+i]
			if x > sol
				sol = x
			end
		end
		puts sol
	end
end
main()

n, k = gets.chomp.split(" ").map(&:to_i)
ss = gets.chomp.split(" ").map(&:to_i)
if n.even? then
  min_box = n / 2
  d = (k - min_box) * 2
else
  min_box = n / 2 + 1
  d = (k - min_box) * 2 + 1
end

res = ss.pop(d)

half = ss.size / 2
right = ss.pop(half).reverse
ss.zip(right).each do |a, b|
  res << a + b
end
puts res.max

def can_put?(weights, k, s)
  return false if weights.last > s
  return weights[0] <= s if weights.size == 1

  used = 0

  ind = 0
  last_ind = weights.size - 1
  while ind <= last_ind
    if weights[ind] + weights[last_ind] > s
      if last_ind > ind
        used += 1
        last_ind -= 1
      else
        used += 1
        ind +=1
        last_ind -= 1
      end
    else
      used += 1
      ind +=1
      last_ind -= 1
    end
  end
  # p [s, used]
  used <= k
end

n,k = $stdin.readline.split.map(&:to_i)
weights = $stdin.readline.split.map(&:to_i)
s = ((0) .. (2*weights.last)).bsearch{|sz|
  can_put?(weights, k, sz)
}

puts s

class Solver
	def main
		n, k = gets.split.map { |x| x.to_i }
		s = gets.split.map { |x| x.to_i }
		k = n if k > n

		ans = 0
		while 2 * k != n do
			ans = [ans, s.pop].max
			k -= 1
			n -= 1
		end

		s = s.zip(s.reverse)
		ans = (s.map { |x| x[0] + x[1] } << ans).max
		puts ans
	end
end

Solver.new.main

def can_put?(weights, k, s)
  return false if weights.last > s
  used = 0
  last_ind = weights.size - 1
  weights.each_index do |ind|
    while weights[ind] + weights[last_ind] > s && last_ind > ind
      last_ind -= 1
      used += 1
    end
    if last_ind == ind
      used += 1
    end
  end
  used <= k
end

n,k = $stdin.readline.split.map(&:to_i)
weights = $stdin.readline.split.map(&:to_i)
s = ((0) .. (2*weights.last)).bsearch{|sz|
  can_put?(weights, k, sz)
}

puts s

def can_put?(weights, k, s)
  return false if weights.last > s

  used = 0

  ind = 0
  last_ind = weights.size - 1
  while ind < last_ind
    while weights[ind] + weights[last_ind] > s && last_ind > ind
      last_ind -= 1
      used += 1
    end
    if ind < last_ind && weights[ind] + weights[last_ind] <= s
      used += 1
      ind +=1
      last_ind -= 1
    elsif ind == last_ind
      used += 1
      last_ind -= 1
    end
  end
  # p [s, used]
  used <= k
end

n,k = $stdin.readline.split.map(&:to_i)
weights = $stdin.readline.split.map(&:to_i)
s = ((0) .. (2*weights.last)).bsearch{|sz|
  can_put?(weights, k, sz)
}

puts s

def can_put?(weights, k, s)
  return false if weights.last > s
  return weights[0] <= s if weights.size == 1

  used = 0

  ind = 0
  last_ind = weights.size - 1
  while ind < last_ind
    while weights[ind] + weights[last_ind] > s && last_ind > ind
      last_ind -= 1
      used += 1
    end
    if ind < last_ind && weights[ind] + weights[last_ind] <= s
      used += 1
      ind +=1
      last_ind -= 1
    elsif ind == last_ind
      used += 1
      last_ind -= 1
    end
  end
  # p [s, used]
  used <= k
end

n,k = $stdin.readline.split.map(&:to_i)
weights = $stdin.readline.split.map(&:to_i)
s = ((0) .. (2*weights.last)).bsearch{|sz|
  can_put?(weights, k, sz)
}

puts s

class Solver
	def main
		n, k = gets.split.map { |x| x.to_i }
		s = gets.split.map { |x| x.to_i }

		ans = 0
		while 2 * k != n do
			ans = [ans, s.pop].max
			k -= 1
			n -= 1
		end

		s = s.zip(s.reverse)
		ans = [s.map { |x| x[0] + x[1] } << ans].max
		ans = s.max
	end
end

Solver.new.main

class Solver
	def main
		n, k = gets.split.map { |x| x.to_i }
		s = gets.split.map { |x| x.to_i }

		ans = 0
		while 2 * k != n do
			ans = [ans, s.pop].max
			k -= 1
			n -= 1
		end

		s = s.zip(s.reverse)
		ans = [s.map { |x| x[0] + x[1] } << ans].max
		puts ans
	end
end

Solver.new.main


Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.

n = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
done = Array.new(n, false)
count = 0
ans = 0
n.times do |time|
  next if count == n

  n.times do |p|
    pos = (time % 2 == 0) ? p : (n - 1) - p
    next if done[pos]
    next if count < arr[pos]
    done[pos] = true
    count += 1
  end

  ans += 1
end

puts ans - 1

n = gets.to_i
s = [nil]+gets.split(" ").map(&:to_i)
p = 0
i = 1
d = 1
c = 0

while p < n

	if s[i] && s[i] <= p
		s[i] = nil
		p += 1
	end

	break if p == n
	if i == n && d == 1
		d = -1
		c += 1
	elsif i == 1 && d == -1
		d = 1
		c += 1
	end
	i += d
end

p c

pieces_of_info, change_dir, position, increasing, cleared_computers = 0,0,0,true,0
n, computers = gets.chomp.to_i, gets.chomp.split(" ").map(&:to_i)
loop do
	if computers[position] <= pieces_of_info and computers[position] != -1
		pieces_of_info += 1
		cleared_computers += 1
		computers[position] = -1
	end

	break if n == cleared_computers

	if increasing
		if position == n-1
			change_dir += 1
			position -= 1
			increasing = false
		else
			position +=1
		end
	else
		if position == 0
			change_dir += 1
			position += 1
			increasing = true
		else
			position -=1
		end
	end
end
puts change_dir

n = gets.chomp.to_i;
arr = gets.chomp.split.map(&:to_i);
info = 0;
ans = 0;
n.times do |i|

  n.times do |j|
    if (arr[j] <= info)
      info += 1
      arr[j] = n + 2;
    end
  end;
  break if (info >= n);
  arr = arr.reverse;
  ans += 1;
end

puts ans;

n=gets.to_i
x=gets.split.map{|e| e.to_i}
ans=-1
i=0
while !x.empty?
	ans+=1
	y=[]
	while !x.empty?
		if x[0]<=i then
			i+=1
		else
			y.unshift(x[0])
		end
		x.shift()
	end
	x=y
end
puts ans

def done?(h, n)
  h.length == n
end

def main
  n = gets.chomp.to_i
  a = gets.chomp.split.map {|i| i.to_i}

  count = 0
  info = 0
  h = {}
  while true
    n.times do |i|
      if not h[i]
        if a[i] <= info
          h[i] = :done
          info += 1
        end
      end
    end

    if done? h, n
      break
    end

    count += 1

    n.times do |i|
      if not h[n-i-1]
        if a[n-i-1] <= info
          h[n-i-1] = :done
          info += 1
        end
      end
    end

    if done? h, n
      break
    end

    count += 1

  end
  puts count

end

main

n = gets.to_i
a = gets.split.map(&:to_i)
info, ans = 0, 0
n.times do |i|
  b = i.even? ? 0.upto(n - 1) : (n - 1).downto(0)
  b.each do |i|
    if a[i] <= info
      info += 1
      a[i] = 1010
    end
  end
  break if info == n
  ans += 1
end
puts ans

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

c = t = 0
while c < a.length
  0.upto(a.length - 1) do |i|
    if a[i] >= 0 and a[i] <= c
      c += 1
      a[i] = -1
    end
  end

  break if c == a.length
  t += 1

  (a.length - 1).downto(0) do |i|
    if a[i] >= 0 and a[i] <= c
      c += 1
      a[i] = -1
    end
  end

  t += 1 if c < a.length
end

puts t.to_s


You have an $$$n \times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \leq x \leq n$$$ and $$$1 \leq y \leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side.  Such arrangement of $$$3$$$ rooks on the $$$4 \times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard or report that there is no such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq k \leq n \leq 40$$$) — the size of the chessboard and the number of rooks.

If there is a stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.

NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \times 3$$$ chessboard to get stable arrangement.

def solve(n, k)
  limit = k

  if (n - (1 - n % 2)) / 2 + 1< k
    return puts '-1'
  else
    result = []

    for i in (1..n)
      row = []

      for j in (1..n)

        if i == j && i % 2 == 1 && limit > 0
          row << 'R'
          limit -= 1
        else
          row << '.'
        end
      end

      result << row
    end

    result.each { puts _1.join }
  end

end

tests = STDIN.gets.to_i
inputs = []

for i in (1..tests)
  n, k = STDIN.gets.split(' ').map(&:to_i)

  inputs << [n, k]
end

inputs.each do |(n, k)|
  solve(n, k)
end

#!/usr/bin/env ruby

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

  if (n + 1) / 2 < k
    puts -1
    next
  end

  fld = Array.new(n) { '.' * n }
  k.times { |i|
    fld[i * 2][i * 2] = 'R'
  }

  puts fld.join "\n"
end

gets
$<.each do
  n,k=_1.split.map &:to_i
  if n<2*k-1
    puts -1
    next
  end
  n.times do |i|
    s="."*n
    s[i]=?R if i.even? && (i+1)/2<k
    puts s
  end
end

def solve(n, k)
  limit = k

  if (n / 3) + 1 < k
    return puts '-1'
  else
    result = []

    for i in (1..n)
      row = []

      for j in (1..n)

        if i == j && i % 2 == 1 && limit > 0
          row << 'R'
          limit -= 1
        else
          row << '.'
        end
      end

      result << row
    end

    result.each { puts _1.join }
  end

end

tests = STDIN.gets.to_i
inputs = []

for i in (1..tests)
  n, k = STDIN.gets.split(' ').map(&:to_i)

  inputs << [n, k]
end

inputs.each do |(n, k)|
  solve(n, k)
end

def solve
  n, k = STDIN.gets.split(' ').map(&:to_i)

  limit = k

  if (n / 3) + 1 < k
    return puts '-1'
  else
    result = []

    for i in (1..n)
      row = []

      for j in (1..n)

        if i == j && i % 2 == 1 && limit > 0
          row << 'R'
          limit -= 1
        else
          row << '.'
        end
      end

      result << row
    end

    result.each { puts _1.join }
  end

end

tests = STDIN.gets.to_i

for i in (1..tests)
  solve
end


Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 ≥ x a1 + a2 + ... + an ≤ y

The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator.

Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.

input = $stdin.readline.split(' ')
n = input[0].to_i; x = input[1].to_i; y=input[2].to_i
a = Array.new(n, 1)

square_sum = n; sum = n
i = 0

until square_sum >= x do
  if sum > y then
    puts -1
    exit
  end
  square_sum -= a[i] * a[i]; a[i]+= 1; sum += 1; square_sum += a[i] * a[i]

end

if sum > y then
  puts -1
  exit
end

a.each do |i| print "#{i} " end
print "\n"

n, x, y = gets.split.map(&:to_i)
t = n - 1
u = y - t
if u * u + t >= x and y >= n
  puts "1\n" * (n - 1) + "#{u}"
else
  puts -1
end

n,x,y=gets.split.map(&:to_i)
if y<n
	a=-1
else
	if (n-1)+(y-n+1)**2>=x
		a=[1]*(n-1)
		a<<y-n+1
	else
		a=-1
	end

end
puts a


Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples:  if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$$$;  if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$$$;  if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows.

Th first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of windows in the building.

For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  n_orig = n
  d = 0
  if n >= 20
    d = n / 10 - 1
    n = n % 10 + 10
  end
  k3, k5, k7 = [0, d * 2, 0]
  catch :found do
    (0..5).each do |i|
      (0..5).each do |j|
        (0..5).each do |k|
          if 3 * i + 5 * j + 7 * k == n
            k3 += i
            k5 += j
            k7 += k
            throw :found
          end
        end
      end
    end
  end
  if k3 * 3 + k5 * 5 + k7 * 7 == n_orig
    puts [k3, k5, k7].join(' ')
  else
    puts -1
  end
end


Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.

The first line contains two positive integers n and m (2 ≤ n ≤ 2·105, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres. The second line contains a sequence a1, a2, ..., an, where ai (1 ≤ ai ≤ m) equals the genre of the i-th book. It is guaranteed that for each genre there is at least one book of that genre.

Print the only integer — the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2·109.

NoteThe answer to the first test sample equals 5 as Sasha can choose:  the first and second books,  the first and third books,  the first and fourth books,  the second and third books,  the third and fourth books.

h=Hash.new(0)
n=gets.to_i
gets.split.each{|e|h[e.to_i]+=1}
r=n*(n-1)/2
h.each{|k,v|r-=v*(v-1)/2}
p r

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
a = a.sort
b = []
for i in 1..m do
  b[i] = 0
end
a.each do |val|
  b[val] += 1
end

combinations = 0
for i in 1..m do
  combinations += b[i] * (n - b[i])
  n -= b[i]
end
puts combinations

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|r,e| r[e]+=1;r} end
############################################################

n, m = gis
a = vcount(gis,[0]*m.succ)

puts (1..m).inject(0){|r,i| (i+1..m).inject(r){|r,j|r+a[i]*a[j]} }

data1=gets.chomp.split
n=data1[0].to_i
m=data1[1].to_i

data2=gets.chomp.split

books=[]

data2.each do |i|
	books.push(i.to_i)
end

books.sort!

books1=[]
b=books[0]
s=0
books.each do |item|
	if item == b
		s+=1
	else
		books1.push(s)
		b=item
		s=1
	end
end

books1.push(s)

sum=0
sum+=(n*(n-1))/2

for i in(0..books1.length-1)
	sum-=(books1[i]*(books1[i]-1))/2
end

puts sum

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
freqs = Hash.new(0)
a = gets.split.map(&:to_i)
a.each do |_a|
  freqs[_a] += 1
end
ans = n * (n - 1) / 2
freqs.each_pair do |k, v|
  ans -= (v * (v - 1) / 2)
end
puts ans

arr1 = gets.chomp.split(/ /)
t = arr1[0].to_i
n = arr1[1].to_i
arr2 = gets.chomp.split(/ /)
arr2.sort!
#puts arr2
arr3 = Array.new(n, 0)
index=0
loop do
	break if index>=t
	arr3[arr2[index].to_i-1]+=1
	index+=1
end

sum=0
count=0

index=0
loop do
	break if index>=n-1
	count = count + arr3[index]
	sum = sum + arr3[index]*(t-count)
	index+=1
	#puts "Index is #{index} and sum is #{sum} and count is #{count}"
end

puts sum

n,m = gets.split(" ").map {|x| x.to_i }
a = gets.split(" ").map{|x| x.to_i}
b = Array.new(m, 0)

remain = n
a.each do |x|
  b[x-1] += 1
end

result = 0
b.each do |x|
  remain -= x
  result += remain* x
end

puts result

n, m = gets.chomp.split(" ").map(&:to_i)
books = gets.chomp.split(" ").map(&:to_i)
dic = Hash.new(0)
res = 0
books.each do |k|
  dic[k] += 1
end
(1..m).to_a.combination(2) do |i, j|
    res +=  dic[i] * dic[j]
end
puts res

n, m = gets.split(' ')
array = gets.split(' ')
sta = Array.new(m.to_i, 0)
for item in array
    sta[item.to_i - 1] += 1
end
ans = 0
for i in 0..m.to_i-1
    for j in i+1..m.to_i-1
        ans += sta[i] * sta[j]
    end
end
puts ans

n, m = gets.split.map(&:to_i)
books = gets.split.map(&:to_i)
genre = Array.new(m)
for book in books
  if genre[book] == nil
    genre[book] = 1
  else
    genre[book] += 1
  end
end

count = 0
for i in (1..m-1)
  for j in (i+1..m)
    count += genre[i] * genre[j]
  end
end

puts count

# http://codeforces.com/problemset/problem/378/B
n, m = gets.chomp.split.map(&:to_i)

list = gets.chomp.split.map(&:to_i)
hash = Hash.new { |hash, key| hash[key] = 0 }

for i in 0..(list.length - 1)
  hash[list[i]] += 1
end

new_list = hash.values
result = 0
for i in 0..(new_list.length - 1)
  for j in (i+1)..(new_list.length - 1)
    result += new_list[j] * new_list[i]
  end
end

puts result

n = 0
m = Array.new

args = gets.chomp.split(/ /)
m = args.last.to_i

genre = Array.new
for i in 0..m do genre[i] = 0 end

arr = gets.chomp.split(/ /)
arr.each {|el| genre[el.to_i - 1] = genre[el.to_i - 1] + 1}

s = genre[0]
ans = 0
for i in 1..m do
	ans = ans + s * genre[i]
	s = s + genre[i];
end

print ans


You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.

Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.

n=gets.to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
c=[0]*n
i=0;
j=n-1
while i<=j
    c[i]=c[j]=(n-i)*(i+1)
    i+=1
    j-=1
end

i=-1
c.map!{|e| e*a[i+=1]}.sort!
b.sort!.reverse!

res=0
c.zip(b){|x, y| res+=x*y%998244353 }
puts res%998244353

n=gets.to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
c=[0]*n
x=0
i=0;
j=n-1
m=n
while i<=j
    c[i]=c[j]=m+x
    m-=1
    x=c[i]-i-1
    i+=1
    j-=1
end

i=-1
c.map!{|e| e*a[i+=1]}.sort!
b.sort!.reverse!

res=0
c.zip(b){|x, y| res+=x*y%998244353 }
puts res


As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...

The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).

Output YES if the string s contains heidi as a subsequence and NO otherwise.

NoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p.

str = gets().to_s
if str.include?("h")
  nul = ""
  str = nul.insert(0, str[str.index("h")+1...str.size])
  if str.include?("e")
    nul = ""
    str = nul.insert(0, str[str.index("e")+1...str.size])
    if str.include?("i")
      nul = ""
      str = nul.insert(0, str[str.index("i")+1...str.size])
      if str.include?("d")
        nul = ""
        str = nul.insert(0, str[str.index("d")+1...str.size])
        if str.include?("i")
            nul = ""
            puts "YES"
          else
            puts "NO"
          end
      else
        puts "NO"
      end
    else
      puts "NO"
    end
  else
    puts "NO"
  end
else
  puts "NO"
end

if gets().to_s.include?('heidi')
  puts "YES"
else
  puts "NO"
end

if gets().to_s.include?('heidi')
  puts "NO"
else
  puts "YES"
end


You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of ancestors $$$b$$$ containing $$$n$$$ numbers: $$$b_i$$$ is an ancestor of the vertex with the number $$$i$$$. The ancestor of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the ancestor of $$$5$$$ is $$$1$$$.The root has no ancestor, so for it, the value of $$$b_i$$$ is $$$i$$$ (the root is the only vertex for which $$$b_i=i$$$).For example, if $$$n=5$$$ and $$$b=[3, 1, 3, 3, 1]$$$, then the tree looks like this.    An example of a rooted tree for $$$n=5$$$, the root of the tree is a vertex number $$$3$$$. You are given an array $$$p$$$ — a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $$$p$$$.In other words, for a given permutation of vertices $$$p$$$, it is necessary to choose such edge weights so that the condition $$$dist[p_i]<dist[p_{i+1}]$$$ is true for each $$$i$$$ from $$$1$$$ to $$$n-1$$$. $$$dist[u]$$$ is a sum of the weights of the edges on the path from the root to $$$u$$$. In particular, $$$dist[u]=0$$$ if the vertex $$$u$$$ is the root of the tree.For example, assume that $$$p=[3, 1, 2, 5, 4]$$$. In this case, the following edge weights satisfy this permutation:  the edge ($$$3, 4$$$) has a weight of $$$102$$$;  the edge ($$$3, 1$$$) has weight of $$$1$$$;  the edge ($$$1, 2$$$) has a weight of $$$10$$$;  the edge ($$$1, 5$$$) has a weight of $$$100$$$. The array of distances from the root looks like: $$$dist=[1,11,0,102,101]$$$. The vertices sorted by increasing the distance from the root form the given permutation $$$p$$$.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test. Each test case consists of three lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that the $$$b$$$ array encodes some rooted tree. The third line contains the given permutation $$$p$$$: $$$n$$$ of different integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each set of input data print the answer on a separate line. If the solution exists, print an array of $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$, where $$$w_i$$$ is the weight of the edge that leads from $$$b_i$$$ to $$$i$$$. For the root there is no such edge, so use the value $$$w_i=0$$$. For all other vertices, the values of $$$w_i$$$ must satisfy the inequality $$$1 \le w_i \le 10^9$$$. There can be equal numbers among $$$w_i$$$ values, but all sums of weights of edges from the root to vertices must be different and satisfy the given permutation. If there are several solutions, output any of them. If no solution exists, output -1.

NoteThe first set of input data of the example is analyzed in the main part of the statement.In the second set of input data of the example, it is impossible to assign the positive weights to obtain a given permutation of vertices.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  b = gets.split.map(&:to_i)
  b.unshift(-1)
  p = gets.split.map(&:to_i)
  g = Array.new(n+1){Array.new}
  root = -1
  1.upto(n) do |i|
    if b[i] == i
      root = i
    else
      g[b[i]] << i
    end
  end
  pp = []
  n.times do |i|
    pp << [p[i],i]
  end
  pp.sort_by!{|pi,i|i}
  f = true
  f = false if pp[0][0] != root

  dist = Hash.new(-2)
  dist[root] = 0
  arr = []
  max = -1
  pp.each do |pi,i|
    pre = b[pi]
    if dist[pre] == -2
      f = false
    else
      d = max - dist[pre] + 1
      arr[pi-1] = d
      max += 1
      dist[pi] = max
    end
  end
  if f
    ans << arr
  else
    ans << [-1]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end


You are given an array $$$a$$$ of $$$n$$$ integers.You want to make all elements of $$$a$$$ equal to zero by doing the following operation exactly three times:  Select a segment, for each number in this segment we can add a multiple of $$$len$$$ to it, where $$$len$$$ is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of $$$a$$$ equal to zero.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100\,000$$$): the number of elements of the array. The second line contains $$$n$$$ elements of an array $$$a$$$ separated by spaces: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).

The output should contain six lines representing three operations. For each operation, print two lines:   The first line contains two integers $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): the bounds of the selected segment.  The second line contains $$$r-l+1$$$ integers $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): the numbers to add to $$$a_l, a_{l+1}, \ldots, a_r$$$, respectively; $$$b_i$$$ should be divisible by $$$r - l + 1$$$.

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
if n != 1
  puts "1 #{n}"
  n.times do |i|
    v = ((n-1) - a[i] % (n-1)) * n
    a[i] += v
    print "#{v} "
  end
  puts ""
  puts "1 #{n-1}"
  (n-1).times do |i|
    print "#{-a[i]} "
  end
  puts ""
  puts "#{n} #{n}"
  puts -a[n-1]
else
  puts "1 1"
  puts -a[0]
  puts "1 1"
  puts "0"
  puts "1 1"
  puts "0"
end


In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.Your task is to paint a cardiogram by given sequence ai.

The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.

Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print  characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.

NoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt

# Print cardiogram given 2d array
def print_cardiogram(out)
    for i in 0..(out.length - 1) do
        puts out[i].join("")
    end
end

# Read Input
n = gets.strip.to_i
a = gets.strip.split.map{|s| s.to_i}

# Find output size and starting point
hd = 0; pp = 0; pn = 0; w = 0;
for i in 0..(a.length - 1) do
    if i.even?
        hd = hd + a[i]
        pp = hd if hd > pp
    else
        hd = hd - a[i]
        pn = hd if hd < pn
    end
    w = w + a[i]
end
h = [pp,0].max - [pn,0].min
y = pp - 1; x = 0;

# Create out array
out = Array.new(h) {Array.new(w){" "}}

# Fill out array
for i in 0..(a.length - 1) do
    for j in 1..a[i] do
        if i.even?
            out[y][x] = "/"
            y = y - 1 if j < a[i]
        else
            out[y][x] = "\\"
            y = y + 1 if j < a[i]
        end
        x = x + 1
    end
end

# Print cardiogram
print_cardiogram(out)

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

coords = [[0,0]]

(0..tab.size-1).each do |i|
    if i % 2 == 0
        coords << [coords[i][0] + tab[i], coords[i][1] + tab[i]]
    else
        coords << [coords[i][0] + tab[i], coords[i][1] - tab[i]]
    end
end

x = coords.map{|a| a[0]}
y = coords.map{|a| a[1]}

x_diff = x.max
y_diff = y.max - y.min

zero = y.max

coords.map!{|x| [x[0], zero-x[1]]}

result = []
(y_diff+1).times do
    result << [' '] * x_diff
end

(0..coords.size-2).each do |i|
    if i % 2 == 0
        temp = 0
        while coords[i][0] + temp != coords[i+1][0]
            result[coords[i][1]-temp][coords[i][0]+temp] = "/"
            temp += 1
        end
    else
        temp = 0
        while coords[i][0] + temp != coords[i+1][0]
            result[coords[i][1]+temp+1][coords[i][0]+temp] = "\\"
            temp += 1
        end
    end

end

result[1..-1].each do |row|
    puts row.join("")
end


Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.

The first line contains integer n (3 ≤ n ≤ 100) — amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 — the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.

If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.

f,g=open("input.txt","r"),open("output.txt","w")
f.gets
g.puts(f.gets[/1.+1/].chop.scan(/10*/).map(&:size).uniq.size<2 ? "YES" : "NO")
f.close
g.close

a, b = [], []
open('input.txt').read.split("\n")[1].each_char.with_index { |c, i| a.push i if c == "1" }
a[0].step(a[-1], a[1] - a[0]) { |e| b.push << e }
open('output.txt','w').print a == b ? :YES : :NO

File.open('input.txt', 'r') do |inp|
	File.open('output.txt', 'w') do |out|
		a = inp.readlines[1].chars.to_a.each_with_index.reduce([]) { |s, (x, i)| s <<= i if x == '1'; s }
		out.write %w[YES NO][Array(1...a.length).reduce([]) { |s, x| s << a[x] - a[x - 1] }.sort.uniq.length == 1 ? 0 : 1]
	end
end

$stdin = File.open("input.txt", "r")
$stdout = File.open("output.txt", "w")
n = gets.to_i
s = gets
ones = (0...n).select{|pos| s[pos]=="1"}
diff = ones.map.with_index(1){|e,i| ones[i]-e if ones[i]}.compact
puts (diff.all?{|x| x == diff[0]} ? "YES" : "NO")

a, b = [], []
p STDIN.read.split("\n")[1]

File.open('input.txt').each { |line|
    puts line
}

File.open('input.txt').each { |line|
    open('output.txt','w').puts line
}

a, b = [], []; gets
#test
# gets.strip.each_char.with_index { |c, i| a.push i if c == "1" }
#a[0].step(a[-1], a[1] - a[0]) { |e| b.push << e }
#print a == b ? :YES : :NO


Luca has a cypher made up of a sequence of $$$n$$$ wheels, each with a digit $$$a_i$$$ written on it. On the $$$i$$$-th wheel, he made $$$b_i$$$ moves. Each move is one of two types:   up move (denoted by $$$\texttt{U}$$$): it increases the $$$i$$$-th digit by $$$1$$$. After applying the up move on $$$9$$$, it becomes $$$0$$$.  down move (denoted by $$$\texttt{D}$$$): it decreases the $$$i$$$-th digit by $$$1$$$. After applying the down move on $$$0$$$, it becomes $$$9$$$.     Example for $$$n=4$$$. The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of wheels. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 9$$$) — the digit shown on the $$$i$$$-th wheel after all moves have been performed. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains the integer $$$b_i$$$ ($$$1 \leq b_i \leq 10$$$) and $$$b_i$$$ characters that are either $$$\texttt{U}$$$ or $$$\texttt{D}$$$ — the number of moves performed on the $$$i$$$-th wheel, and the moves performed. $$$\texttt{U}$$$ and $$$\texttt{D}$$$ represent an up move and a down move respectively.

For each test case, output $$$n$$$ space-separated digits  — the initial sequence of the cypher.

3

3

9 3 1

3 DDD

4 UDUU

2 DU

2

0 9

9 DDDDDDDDD

9 UUUUUUUUU

5

0 5 9 8 3

10 UUUUUUUUUU

3 UUD

8 UUDUUDDD

10 UUDUUDUDDU

4 UUUU

NoteIn the first test case, we can prove that initial sequence was $$$[2,1,1]$$$. In that case, the following moves were performed:   On the first wheel: $$$2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{D}]{} 9$$$.  On the second wheel: $$$1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{U}]{} 3$$$.  On the third wheel: $$$1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{U}]{} 1$$$.  The final sequence was $$$[9,3,1]$$$, which matches the input.

#!/usr/bin/env ruby

# https://codeforces.com/contest/1703/problem/C

t = gets.chomp.to_i # tests

(1..t).each do |numtest|
  n = gets.chomp.to_i # wheels
  l = gets.chomp # final state
  state = l.split(' ').map(&:to_i)
  #puts "final state=#{state}"
  (0..n-1).each do |numwheel|
    #puts "numwheel=#{numwheel}"
    m = gets.chomp
    pm = m.split(' ')
    #puts "pm=#{pm}"
    (0..pm[0].to_i-1 ).each do |i|
      #puts "i=#{i}"
      if pm[1][i] == 'U'
        state[numwheel] = state[numwheel] == 0 ? 9 : state[numwheel] - 1
      elsif pm[1][i] == 'D'
        state[numwheel] = state[numwheel] == 9 ? 0 : state[numwheel] + 1
      else
        echo "Problem with character #{i} that is #{pm[1][i]}"
        exit 1;
      end
      #puts "state=#{state}"
    end
  end
  puts state.join(' ')

end

t = gets.to_i

t.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  n.times do |i|
    b = gets.chomp
    a[i] = (a[i] + b.count('D') - b.count('U')) % 10
  end
  puts a*' '
end

gets.to_i.times {
	n = gets.to_i
	k = gets.split.map(&:to_i)
	n.times { |x|
		m, ud = gets.split
		u = ud.chars.count {|x| x == 'U'}
		d = m.to_i -  u
		print (k[x] - u + d)%10, ' '
	}
	puts ''
}

def cypher(n, str, a)
  i = 0
  res = a
  while n-1 >= 0
    if str[i] == "D"
      res += 1
    else
      res -= 1
    end
    n -= 1
    i += 1
  end
  res % 10
end
t = gets.chomp.to_i
final = []

(0..t-1).each do |i|
  inputs = []
  x = 0
  n = gets.chomp.to_i
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)

  (0..n-1).each do |j|
    combination = gets.chomp
    combination = combination.split(" ")
    combination.push(arr[x])
    inputs.push(combination)
    x+=1
  end
  final.push(inputs)
end

final.each do |input|
  ans = ""
  input.each do |i|
    x = cypher(i[0].to_i, i[1], i[2])
    ans += "#{x} "
  end

  puts ans.strip
end


Word $$$s$$$ of length $$$n$$$ is called $$$k$$$-complete if   $$$s$$$ is a palindrome, i.e. $$$s_i=s_{n+1-i}$$$ for all $$$1 \le i \le n$$$;  $$$s$$$ has a period of $$$k$$$, i.e. $$$s_i=s_{k+i}$$$ for all $$$1 \le i \le n-k$$$. For example, "abaaba" is a $$$3$$$-complete word, while "abccba" is not.Bob is given a word $$$s$$$ of length $$$n$$$ consisting of only lowercase Latin letters and an integer $$$k$$$, such that $$$n$$$ is divisible by $$$k$$$. He wants to convert $$$s$$$ to any $$$k$$$-complete word.To do this Bob can choose some $$$i$$$ ($$$1 \le i \le n$$$) and replace the letter at position $$$i$$$ with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.Note that Bob can do zero changes if the word $$$s$$$ is already $$$k$$$-complete.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t\le 10^5$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$, $$$n$$$ is divisible by $$$k$$$). The second line of each test case contains a word $$$s$$$ of length $$$n$$$. It is guaranteed that word $$$s$$$ only contains lowercase Latin letters. And it is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer, representing the minimum number of characters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.

4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp

NoteIn the first test case, one optimal solution is aaaaaa.In the second test case, the given word itself is $$$k$$$-complete.

gets.to_i.times do
 n, k = gets.split(' ').map(&:to_i)
 word = gets.chomp

 changes_count = 0
 letter_count = {}

 i = 0
 if k > 1
  while i < k/2 do
   j = 0
   while i+k*j < n-1
    letter_count[word[i+k*j]].nil? ?
     letter_count[word[i+k*j]] = 1 :
     letter_count[word[i+k*j]] += 1

    letter_count[word[k-1-i+k*j]].nil? ?
     letter_count[word[k-1-i+k*j]] = 1 :
     letter_count[word[k-1-i+k*j]] += 1

    j += 1
   end
   changes_count += (n/k)*2 - letter_count.values.max

   letter_count = {}
   i += 1
  end
 end

 if k % 2 == 1
  letter_count = {}
  i = k / 2
  j = 0
  while i + k * j < n
   letter_count[word[i+k*j]].nil? ?
    letter_count[word[i+k*j]] = 1 :
    letter_count[word[i+k*j]] += 1

   j+= 1
  end
  changes_count += (n/k) - letter_count.values.max
 end

 puts changes_count
end

gets.to_i.times do
 n, k = gets.split(' ').map(&:to_i)
 word = gets.chomp

 changes_count = 0
 i = 0

 while i < k/2 do
  letter_count = Hash.new(0)
  j = 0

  while j < n/k
   letter_count[word[i+k*j]] += 1
   letter_count[word[k-1-i+k*j]] += 1
   j += 1
  end

  changes_count += (n/k)*2 - letter_count.values.max
  i += 1
 end

 if k % 2 == 1
  letter_count = Hash.new(0)
  i, j = k/2, 0

  while j < n/k
   letter_count[word[i+k*j]] += 1
   j+= 1
  end

  changes_count += (n/k) - letter_count.values.max
 end

 puts changes_count
end

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  s = gets.chomp
  count = 0
  for i in 0...(k / 2) do
    hash = Hash.new(0)
    for j in 0...(n / k) do
      hash[s[i + k * j]] += 1
      hash[s[k - 1 - i + k * j]] += 1
    end
    count += (n / k * 2) - hash.values.max
  end
  if k % 2 == 1
    hash = Hash.new(0)
    for j in 0...(n / k) do
      hash[s[k / 2 + k * j]] += 1
    end
    count += (n / k) - hash.values.max
  end
  puts count
end

gets.to_i.times do
 n, k = gets.split(' ').map(&:to_i)
 word = gets.chomp

 changes_count = 0
 letter_count = {}

 i = 0
 if k > 1
  while i < k/2 do
   j = 0
   while i+k*j < n-1
    letter_count[word[i+k*j]].nil? ?
     letter_count[word[i+k*j]] = 1 :
     letter_count[word[i+k*j]] += 1

    letter_count[word[k-1-i+k*j]].nil? ?
     letter_count[word[k-1-i+k*j]] = 1 :
     letter_count[word[k-1-i+k*j]] += 1

    j += 1
   end
   changes_count += (n/k)*2 - letter_count.values.max

   letter_count = {}
   i += 1
  end
 end

 if k % 2 == 1
  letter_count = {}
  i = k / 2
  j = 0
  while i + k * j < n-1
   letter_count[word[i+k*j]].nil? ?
    letter_count[word[i+k*j]] = 1 :
    letter_count[word[i+k*j]] += 1
   j+= 1
  end
  changes_count += (n/k) - letter_count.values.max
 end

 puts changes_count
end


Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?

In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n,  - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.

Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.

NoteThe following image represents possible process of removing leaves from the tree:

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, false]]
while !_stack.empty?
  node, sum_cur, kill = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max

    kill_n = sum_cur_n > verts[node_nxt-1] || kill
    removed += 1 if kill_n
    _stack.push([node_nxt, sum_cur_n, kill_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, 0, false]]
while !_stack.empty?
  node, sum_max, sum_cur, kill = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max
    sum_max_n = [sum_cur_n, sum_max].max

    kill_n = sum_max_n > verts[node_nxt-1] || kill
    removed += 1 if kill_n
    _stack.push([node_nxt, sum_max_n, sum_cur_n, kill_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, 0]]
while !_stack.empty?
  node, sum_max, sum_cur = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max
    sum_max_n = [sum_cur_n, sum_max].max
    if sum_max_n > verts[node_nxt-1]
      removed += 1
    end
    _stack.push([node_nxt, sum_max_n, sum_cur_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0]]
while !_stack.empty?
  node, w_acc = _stack.pop
  (g[node] || []).each do |node_nxt, w_nxt|
    w_acc_nxt = [w_acc + w_nxt, w_acc].max
    if w_acc_nxt > verts[node_nxt-1]
      removed += 1
    end
    _stack.push([node_nxt, w_acc_nxt])
  end
end

puts removed