After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.

The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≤ di ≤ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.

Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.

NoteConsider the first sample.  Initially Kay and Gerda have 7 packs of ice cream.  Carrier brings 5 more, so now they have 12 packs.  A kid asks for 10 packs and receives them. There are only 2 packs remaining.  Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed.  Carrier bring 40 packs, now Kay and Gerda have 42 packs.  Kid asks for 20 packs and receives them. There are 22 packs remaining.

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
r=0
n.times{
	a,b=gets.split.zip([:to_s,:to_i]).map{|x,y|x.send(y)}
	if a=='-'
		if b>x
			r+=1
		else
			x-=b
		end
	else
		x+=b
	end
}
puts [x,r]*' '

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

n, x = I[]
z = 0
n.times{
  a, b = gets.split
  b = b.to_i
  if a == '+'
    x += b
  else
    if x < b
      z += 1
    else
      x -= b
    end
  end
}

print x, ' ', z

n, x = gets.chomp.split.map(&:to_i)
d = 0
n.times do
  op, num = gets.chomp.split.map { |a| a.to_i.to_s == a ? a.to_i : a }

  if op == '+'
    x += num
  else
    if num > x
      d += 1
    else
      x -= num
    end
  end
end
puts [x, d].join(' ')

loobnum , ice = gets.chomp.split.map(&:to_i)
ch = 0
while loobnum > 0
    sign , num = gets.chomp.split.map(&:to_s)
    num = num.to_i
    if sign == '-'
        if num > ice
            ch += 1
        else
            ice = ice - num
        end
    elsif sign == '+'
        ice = ice + num
    end
    loobnum -= 1
end

print "#{ice} " " #{ch}"

n, x = gets.split.map(&:to_i)
ans = 0
n.times do
  op, num = gets.split
  num = num.to_i
  if op == "+"
    x += num
  else
    if x >= num
      x -= num
    else
      ans += 1
    end
  end
end
puts "#{x} #{ans}"

n, x = gets.strip.split.map(&:to_i)
packs = x
distressed = 0
n.times do
    query, d = gets.strip.split
    d = d.to_i
    if query == '+'
        packs += d
    else
        if packs < d
            distressed += 1
        else
            packs -= d
        end
    end
end
puts "#{packs} #{distressed}"

n,x=gets.split.map{|e| e.to_i}
ans=0
n.times{
	c,a=gets.split
	a=a.to_i
	if c=="+" then
		x+=a
	else
		if x<a then
			ans+=1
		else
			x-=a
		end
	end
}
puts [x,ans]*" "

n, x=gets.split.map &:to_i
res=0
n.times{
    c, d=gets.split
    d=d.to_i
    if c==?+
        x+=d
    else
        if x<d
            res+=1
        else
            x-=d
        end
    end
}
puts "#{x} #{res}"

nx = gets.chomp.split.map(&:to_i)
n = nx[0]
x = nx[1]
d = []
for i in (0..n-1)
	d[i] = gets.chomp.split
end

distress = 0
for i in (0..n-1)
	if d[i][0] == "+"
		x += d[i][1].to_i
	else
		if x-d[i][1].to_i < 0
			distress += 1
		else
			x -= d[i][1].to_i
		end
	end
end

print x
print ' '
print distress

#Made By Hasbi Hamza
a = gets.chomp.split(' ').map(&:to_i)
n=a[0].to_i
x=a[1].to_i
left=0
for i in 1..n
  r=gets.chomp.split(' ').map(&:to_s)
  str=r[0].to_s
  tmp=r[1].to_i
  if str=="+" then x+=tmp
  elsif str=="-" and x>=tmp then x-=tmp
  elsif str=="-" and x<tmp then left+=1
  end
end
puts("#{x} #{left}")

n, x = gets.split.map(&:to_i)
puts n.times.map{gets.delete(' ').to_i}.reduce([x,0]){|(x,k),d| x+d<0 ? [x,k+1] : [x+d,k]}.join(' ')

n, x = gets.split.map(&:to_i)
distressed = 0
n.times do
  s, d = gets.chomp.split
  if s == '+'
    x += d.to_i
  else
    if x < d.to_i
      distressed += 1
    else
      x -= d.to_i
    end
  end
end
puts "#{x} #{distressed}"

n, x = gets.split.map(&:to_i)
nsad = 0
n.times do
  s, d = gets.split
  d = d.to_i
  if s == '+'
    x += d
  elsif d <= x
    x -= d
  else
    nsad += 1
  end
end
print x, ' ', nsad

n, count = gets.split(' ').map(&:to_i)
sad = 0

1.upto(n) do
  c, x = gets.split(' ').map { |c| '+-'.include?(c) ? c : c.to_i }

  if c == '+'
    count += x
    next
  end

  if x > count
    sad += 1
    next
  end

  count -= x
end

puts "#{count} #{sad}"

lineNum, initial = gets.chomp.split(' ').map(&:to_i)

ice = initial
child = 0

lineNum.times do
	opCode, amount = gets.chomp.split(' ')

	amount = amount.to_i
	if opCode == "+"
		ice += amount
	elsif opCode == "-"
			if ice >= amount
				ice -= amount
			else
				child += 1
			end
	end
end

puts "#{ice} #{child}"


There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.

For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).

NoteIn the first test case of the example, the optimal sequence of moves can be as follows:  before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$;  choose $$$c=6$$$;  now $$$a=[40, 3, 40, 3, 20, 1]$$$;  choose $$$c=40$$$;  now $$$a=[20, 3, 20, 3, 20, 1]$$$;  choose $$$c=20$$$;  now $$$a=[10, 3, 10, 3, 10, 1]$$$;  choose $$$c=10$$$;  now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.

#!usr/bin/env ruby

#https://codeforces.com/problemset/problem/1277/B

require 'set'

n = gets.to_i

n.times do
 size = gets
 input = gets.split(' ').map(&:to_i)
 counter = Set.new

 input.each do |i|
  while i % 2 == 0 do
   counter.add(i)
   i /= 2
  end
 end

 puts counter.size
end


Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?

The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters.  It is possible that b and c coincide.

Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.

NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.

def next_h
  s = gets.strip
  d = Hash.new(0)
  s.each_char { |i| d[i] += 1 }
  [s, d]
end

def times (a, b)
  b.each.map { |key, value| a[key] / value }.min
end

def minus(a, b, n = 1)
  b.each { |key, value| a[key] -= value * n}
end

def sol(a, b, c, b0, c0)
  a0 = a.dup
  s = [0] * 3
  n = times(a, b)
  0.upto(n) do |bt|
    minus(a, b) if bt > 0
    ct = times(a, c)
    s = [s, [bt + ct, bt, ct]].max
  end
  a = a0
  answer = b0 * s[1] + c0 * s[2]
  minus(a, b, s[1])
  minus(a, c, s[2])
  answer << a.each.map {|k, v| k * v}.join
end

a = next_h[1]
b0, b = next_h
c0, c = next_h
puts sol(a, b, c, b0, c0)

def next_h
  s = gets.strip
  d = Hash.new(0)
  s.each_char { |i| d[i] += 1 }
  [s, d]
end

def minus? (a, b)
  b.each.all? { |key, value| a[key] >= value }
end

def minus(a, b)
  b.each { |key, value| a[key] -= value}
end

def sol(a, b, c, b0, c0)
  count = 0
  str = ''
  while minus?(a, b)
    count += 1
    str << b0
    minus(a, b)
  end
  while minus?(a, c)
    count += 1
    str << c0
    minus(a, c)
  end
  str << a.each.map { |k, v| k * v}.join
  [count, str]
end

a = next_h[1]
b0, b = next_h
c0, c = next_h
b.freeze
c.freeze
puts [sol(a.dup, b, c, b0, c0), sol(a.dup, c, b, c0, b0)].max[1]


Let's say you are standing on the $$$XY$$$-plane at point $$$(0, 0)$$$ and you want to reach point $$$(n, n)$$$.You can move only in two directions:   to the right, i. e. horizontally and in the direction that increase your $$$x$$$ coordinate,  or up, i. e. vertically and in the direction that increase your $$$y$$$ coordinate. In other words, your path will have the following structure:   initially, you choose to go to the right or up;  then you go some positive integer distance in the chosen direction (distances can be chosen independently);  after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than $$$n - 1$$$ direction changes.As a result, your path will be a polygonal chain from $$$(0, 0)$$$ to $$$(n, n)$$$, consisting of at most $$$n$$$ line segments where each segment has positive integer length and vertical and horizontal segments alternate.Not all paths are equal. You have $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the cost of the $$$i$$$-th segment.Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $$$k$$$ segments ($$$k \le n$$$), then the cost of the path is equal to $$$\sum\limits_{i=1}^{k}{c_i \cdot length_i}$$$ (segments are numbered from $$$1$$$ to $$$k$$$ in the order they are in the path).Find the path of the minimum cost and print its cost.

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — the costs of each segment. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

For each test case, print the minimum possible cost of the path from $$$(0, 0)$$$ to $$$(n, n)$$$ consisting of at most $$$n$$$ alternating segments.

NoteIn the first test case, to reach $$$(2, 2)$$$ you need to make at least one turn, so your path will consist of exactly $$$2$$$ segments: one horizontal of length $$$2$$$ and one vertical of length $$$2$$$. The cost of the path will be equal to $$$2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$$$.In the second test case, one of the optimal paths consists of $$$3$$$ segments: the first segment of length $$$1$$$, the second segment of length $$$3$$$ and the third segment of length $$$2$$$.The cost of the path is $$$1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$$$.In the third test case, one of the optimal paths consists of $$$4$$$ segments: the first segment of length $$$1$$$, the second one — $$$1$$$, the third one — $$$4$$$, the fourth one — $$$4$$$. The cost of the path is $$$1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$$$.

def solve(n, c)
  v = (0 ... n).step(2).map { |i| c[i] }
  v_cumsum = v.cum(0, &:+)
  v_cummin = v.cum(INF) { |*xy| xy.min }
  h = (1 ... n).step(2).map { |i| c[i] }
  h_cumsum = h.cum(0, &:+)
  h_cummin = h.cum(INF) { |*xy| xy.min }

  ans = INF
  n.times do |i|
    cost = 0
    iv = i / 2 + 1
    cost += v_cummin[iv] * (n - iv) + v_cumsum[iv]
    ih = (i + 1) / 2
    cost += h_cummin[ih] * (n - ih) + h_cumsum[ih]
    ans = min(ans, cost)
  end

  ans
end

def main
  t = int
  t.times do
    n = int
    c = ints
    puts solve(n, c)
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**18

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def chars; gets.to_s.chomp.chars; end
def rep(n, &b); Array.new(n, &b) end
def yes; puts YESNO[1] end
def no; puts YESNO[0] end
def yesno t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * mod_inv(y, mod) % mod end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main


You are both a shop keeper and a shop assistant at a small nearby shop. You have $$$n$$$ goods, the $$$i$$$-th good costs $$$a_i$$$ coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $$$n$$$ goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $$$n$$$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100)$$$ — the number of goods. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the price of the $$$i$$$-th good.

For each query, print the answer for it — the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

q = gets.to_i
q.times do
  n = gets.to_i
  as = gets.split.map(&:to_f)
  puts (as.inject(:+)/n).ceil
end

t = gets.to_i
z = []
(0..t - 1).each do |i|
  sum = 0
  po = gets
  str = gets
  z[i] = str
  bloc = z[i].split(' ')
  # bloc.map { |w| w = w.to_i}
  bloc.map { |v| sum += v.to_f }
  avg1 = sum/bloc.size
  puts avg1.ceil
end

# coding: utf-8

# if __FILE__ == $0
# end

q = gets.to_i
q.times {
    n = gets.to_i
    a = gets.split.map(&:to_i)
    sum = a.reduce(&:+)
    puts ((sum*1.0)/n).ceil
}

q = gets.to_i
q.times {
  n = gets.to_i
  a = gets.split.map(&:to_i)
  p (a.inject(:+) * 1.0 / n).ceil
}

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

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

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

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

q.times do |i|
  n = gi
  a = gsmi
  sum = sum(a)
  ans <<(sum/n.to_f).ceil
end

puts ans

q = gets.to_i
q.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  s = a.inject(0) { |s, x| s + x }
  puts (s + n - 1)/n
end

1.upto(gets.to_i) do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i).inject(&:+)
  puts a.div(n) + (a.modulo(n).zero? ? 0 : 1)
end


You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print "YES" if it is possible to make all elements zero, otherwise print "NO".

NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations:   Decrease $$$a_1$$$ and $$$a_2$$$,  Decrease $$$a_3$$$ and $$$a_4$$$,  Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.

gets
s = gets.split.map(&:to_i).sort.reverse
puts (((s.inject(:+) % 2) == 0) && s[0] <= s.drop(1).inject(:+) ? :YES : :NO)

n = gets.to_i
as = gets.split(' ').map(&:to_i)
total = as.reduce(:+)
if total % 2 == 1
  puts "NO"
else
  max = as.max
  if max <= (total - max)
    puts "YES"
  else
    puts "NO"
  end
end

n = gets.to_i
as = gets.split(' ')[0..n].map(&:to_i)
total = as.reduce(:+)
if total % 2 == 1
  puts "NO"
else
  max = as.max
  if max <= (total - max)
    puts "YES"
  else
    puts "NO"
  end
end

def inp_i(array)
  if array == 1
    gets.split.map(&:to_i)
  else
    gets.chomp.to_i
  end
end
def inp_s(array)
  if array == 1
    gets.split.map
  else
    gets.chomp
  end
end
def inp_f(array)
  if array == 1
    gets.split.map(&:to_f)
  else
    gets.chomp.to_f
  end
end
#input temps (shotcuts)
a =inp_i(0)
arr = inp_i(1);
sum = 0 ; arr.each{|i| sum+=i}
if(sum%2==0 and arr.max <= sum-arr.max)
  puts "yes"
else
  puts "no"
end

gets
s = gets.split.map(&:to_i).sort
puts (((s.inject(:+) % 2) == 0) && s[0] <= s.drop(1).inject(:+) ? :YES : :NO)

gets
puts ((gets.split.map(&:to_i).inject(:+) % 2) == 0 ? :YES : :NO)


Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

class C
  def initialize
    n, k = $stdin.gets.chomp.split(' ').map(&:to_i)

    if n < k
      puts -1
      exit
    end

    str = ""

    if k > 2
      time = n - ( k - 2 )

      if time.even?
        str += "ab"*(time/2)
      else
        str += "ab"*(time/2)+"a"
      end

      ch = "c"

      (k-2).times do
        str += ch
        ch = ch.next
      end
    else
      if k == 1 && n > 1
        puts -1
        exit
      elsif k == 1 && n == 1
        puts "a"
        exit
      end

      if n.even?
        str += "ab" * (n/2)
      else
        str += "ab" * (n/2) + "a"
      end
    end

    puts str
  end
end

c = C.new

n, k = gets.split(" ").collect{|x| x.to_i}

if k == 1 and n > 1
  puts "-1"
elsif k == 1 and n == 1
  puts "a"
elsif k > n or k > 26
  puts "-1"
else
  abc = "abcdefghijklmnopqrstuvwxyz"
  s = "ab" * (n/2)
  s += "a" if (n % 2) == 1
  (k-2).times do |x|
    s[s.length-k+2+x] = abc[x+2]
  end
  puts s
end

n,k=gets.split.map(&:to_i)
if n<k
  p -1
  exit
end
if k==1
  if n==1
    puts "a"
  else
    p -1
  end
  exit
end
(1..n-k+2).each{|i| i&1==1?(print 'a'):(print 'b')}
(2..k-1).each{|i| print (('a'.ord+i).chr)}

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

if m == 1 && n != 1 || m > n
  ans = "-1"
elsif m == 1
  ans = "a"
else
  L = n - (m - 2);
  ans = "ab" * (L/2);
  if L % 2 == 1
    ans += "a"
  end
  ans += ('c'..(m + 96).chr).to_a.join('');
end
puts ans

letters = ('c'..'z').to_a.join('')

n, k = gets.chomp.split.map(&:to_i)
if n == 1 && k == 1
  puts 'a'
  exit
end
if k > n || k == 1
  s = -1
else
  p = n - k + 2
  s = 'ab' * (p / 2)
  s += 'a' if p.odd?
  s += letters[0..(n - p - 1)] if n - p > 0
end
puts s

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

if k == 1 && n == 1
  puts 'a'
elsif k > 1 && n >= k
  chars = []
  c = 0
  (n - (k-2)).times do
    chars << c
    c = (c + 1) % 2
  end

  c = 2
  (k-2).times do
    chars << c
    c += 1
  end

  puts chars.map{|x| ('a'.ord + x).chr}.join
else
  puts -1
end

class C
  def initialize
    n, k = $stdin.gets.chomp.split(' ').map(&:to_i)

    if n < k
      puts -1
      exit
    end

    str = ""

    if k > 2
      time = n - ( k - 2 )

      if time.even?
        str += "ab"*time
      else
        str += "ab"*(time/2)+"a"
      end

      ch = "c"

      (k-2).times do
        str += ch
        ch = ch.next
      end
    else
      if k == 1 && n > 1
        puts -1
        exit
      elsif k == 1 && n == 1
        puts "a"
        exit
      end

      if n.even?
        str += "ab" * (n/2)
      else
        str += "ab" * (n/2) + "a"
      end
    end

    puts str
  end
end

c = C.new

n,k=gets.split.map(&:to_i)
if n<k
  p -1
  exit
end
if k==1
  if n==1
    p 'a'
  else
    p -1
  end
  exit
end
(1..n-k+2).each{|i| i&1==1?(print 'a'):(print 'b')}
(2..k-1).each{|i| print (('a'.ord+i).chr)}

n, k = gets.split(" ").collect{|x| x.to_i}

if k == 1 and n > 1
  puts "-1"
elsif k == 1 and n == 1
  puts "a"
elsif k > n or k > 26
  puts "-1"
else
  s = ""
  abc = "abcdefghijklmnopqrstuvwxyz"
  s = "ab" * (n/2)
  s += "a" if n % 2
  (k-2).times do |x|
    s[s.length-k+2+x] = abc[x+2]
  end
  puts s
end

n, k = gets.split(" ").collect{|x| x.to_i}

if k == 1 and n > 1
  puts "-1"
elsif k == 1 and n == 1
  puts "a"
elsif k > n or k > 26
  puts "-1"
else
  abc = "abcdefghijklmnopqrstuvwxyz"
  s = "ab" * (n/2)
  s += "a" if (n % 2) == 1
  puts s
  (k-2).times do |x|
    s[s.length-k+2+x] = abc[x+2]
  end
  puts s
end

letters = ('c'..'z').to_a.join('')

n, k = gets.chomp.split.map(&:to_i)
if k > n || k == 1
  s = -1
else
  p = n - k + 2
  s = 'ab' * (p / 2)
  s += 'a' if p.odd?
  s += letters[0..(n - p - 1)] if n - p > 0
end
puts s

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

if k <= n && (k > 1 || k == n )
  chars = []
  c = 0
  (n - (k-2)).times do
    chars << c
    c = (c + 1) % 2
  end

  c = 2
  (k-2).times do
    chars << c
    c += 1
  end

  puts chars.map{|x| ('a'.ord + x).chr}.join
else
  puts -1
end


Let's define the cost of a string $$$s$$$ as the number of index pairs $$$i$$$ and $$$j$$$ ($$$1 \le i < j < |s|$$$) such that $$$s_i = s_j$$$ and $$$s_{i+1} = s_{j+1}$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Among all strings with length $$$n$$$ that contain only the first $$$k$$$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).

Print the string $$$s$$$ such that it consists of $$$n$$$ characters, each its character is one of the $$$k$$$ first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.

n, k = gets.to_s.split.map {|x| x.to_i }
s = [k - 1] * k
freq = [0] * (k * k)

idx = 1
while idx < n
  bestfreq   = freq[0 + s[idx - 1]]
  bestletter = 0
  1.upto(k - 1) do |letter|
    if (freq[letter * k + s[idx - 1]] < bestfreq)
      bestletter = letter
      bestfreq = freq[letter * k + s[idx - 1]]
    end
  end
  freq[bestletter * k + s[idx - 1]] += 1
  s[idx] = bestletter
  idx += 1
end

printf("%s\n", s.map {|x| x + 'a'.ord}.pack("c" * n))

n, k = gets.to_s.split.map {|x| x.to_i }
s = [0] * k
freq = [0] * (k * k)
singlefreq = [0] * k

idx = 1
singlefreq[0] = 0
while idx < n
  bestfreq   = freq[0 + s[idx - 1]]
  bestletter = 0
  1.upto(k - 1) do |letter|
    if (freq[letter * k + s[idx - 1]] < bestfreq) || (freq[letter * k + s[idx - 1]] == bestfreq && singlefreq[letter] < singlefreq[bestletter])
      bestletter = letter
      bestfreq = freq[letter * k + s[idx - 1]]
    end
  end
  freq[bestletter * k + s[idx - 1]] += 1
  singlefreq[bestletter] += 1
  singlefreq[s[idx - 1]] += 1
  s[idx] = bestletter
  idx += 1
end

printf("%s\n", s.map {|x| x + 'a'.ord}.pack("c" * n))

n, k = gets.to_s.split.map {|x| x.to_i }
s = [0] * k
freq = [0] * (k * k)
singlefreq = [0] * k

idx = 1
singlefreq[0] = 1
while idx < n
  bestfreq   = freq[0 + s[idx - 1]]
  bestletter = 0
  1.upto(k - 1) do |letter|
    if (freq[letter * k + s[idx - 1]] < bestfreq) || (freq[letter * k + s[idx - 1]] == bestfreq && singlefreq[letter] < singlefreq[bestletter])
      bestletter = letter
      bestfreq = freq[letter * k + s[idx - 1]]
    end
  end
  freq[bestletter * k + s[idx - 1]] += 1
  singlefreq[bestletter] += 1
  singlefreq[s[idx - 1]] += 1
  s[idx] = bestletter
  idx += 1
end

printf("%s\n", s.map {|x| x + 'a'.ord}.pack("c" * n))

n, k = gets.to_s.split.map {|x| x.to_i }
s = [0] * k
freq = [0] * (k * k)
singlefreq = [0] * k

idx = 1
singlefreq[0] = 1
while idx < n
  bestfreq   = freq[0 + s[idx - 1]]
  bestletter = 0
  1.upto(k - 1) do |letter|
    if (freq[letter * k + s[idx - 1]] < bestfreq) || (freq[letter * k + s[idx - 1]] == bestfreq && singlefreq[letter] < singlefreq[bestletter])
      bestletter = letter
      bestfreq = freq[letter * k + s[idx - 1]]
    end
  end
  freq[bestletter * k + s[idx - 1]] += 1
  singlefreq[bestletter] += 1
  s[idx] = bestletter
  idx += 1
end

printf("%s\n", s.map {|x| x + 'a'.ord}.pack("c" * n))

n, k = gets.to_s.split.map {|x| x.to_i }
s = [0] * k
freq = [0] * (k * k)

idx = 1
while idx < n
  bestfreq   = freq[0 + s[idx - 1]]
  bestletter = 0
  1.upto(k - 1) do |letter|
    if freq[letter * k + s[idx - 1]] < bestfreq
      bestletter = letter
      bestfreq = freq[letter * k + s[idx - 1]]
    end
  end
  freq[bestletter * k + s[idx - 1]] += 1
  s[idx] = bestletter
  idx += 1
end

printf("%s\n", s.map {|x| x + 'a'.ord}.pack("c" * n))


Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)— the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, print a single value — the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

#!/usr/bin/env ruby

def arline
    gets.chomp.split.map(&:to_i)
end

tc = arline[0]
tc.times do
    n = arline[0]
    ar = arline.sort
    puts (ar.pop + ar.sum.to_f/ar.length)
end

testcases = gets.to_i
testcases.times do
  n = gets.to_i
  arr = gets.split(" ").map!(&:to_f)
  half = (arr.sum - arr.max)/(n-1)
  res = arr.max + half
  puts res.to_f
  testcases -= 1
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i).sort
    sum = 0
    a.each do |i|
        sum += i
    end
    mae = 0
    ushiro = 0
    cnt = 0
    max = -Float::INFINITY
    a.each do |j|
        mae += j
        cnt += 1
        ushiro = sum - mae
        ans = (mae/cnt.to_f) + (ushiro/(n-cnt).to_f) if cnt != n
        max = [max,ans].max if cnt != n
        # puts "~~~~~"
        # p ans
        # puts "==="
    end
    puts max
end

END { load __FILE__ unless $stdin.eof? }

t = gets.to_i

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

	a_max = a.max
	puts a_max + (a.sum - a_max).fdiv(n - 1)
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    sum = 0
    a.each do |i|
        sum += i
    end
    mae = 0
    ushiro = 0
    cnt = 0
    max = -Float::INFINITY
    a.each do |j|
        mae += j
        cnt += 1
        ushiro = sum - mae
        ans = (mae/cnt.to_f) + (ushiro/(n-cnt).to_f) if cnt != n
        max = [max,ans].max if cnt != n
    end
    puts max
end


Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:   Cat A changes its napping place in order: $$$n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically;  Cat B changes its napping place in order: $$$1, 2, 3, \dots, n - 1, n, 1, 2, \dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$) — the number of spots and hour $$$k$$$.

For each test case, print one integer — the index of the spot where cat B will sleep at hour $$$k$$$.

NoteIn the first and second test cases $$$n = 2$$$, so:   at the $$$1$$$-st hour, A is on spot $$$2$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$1$$$ and B — to $$$2$$$.  If $$$n = 3$$$ then:   at the $$$1$$$-st hour, A is on spot $$$3$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$2$$$; B'd like to move from $$$1$$$ to $$$2$$$, but this spot is occupied, so it moves to $$$3$$$;  at the $$$3$$$-rd hour, A moves to spot $$$1$$$; B also would like to move from $$$3$$$ to $$$1$$$, but this spot is occupied, so it moves to $$$2$$$. In the sixth test case:   A's spots at each hour are $$$[5, 4, 3, 2, 1]$$$;  B's spots at each hour are $$$[1, 2, 4, 5, 2]$$$.

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  k -= 1
  puts (k + (n % 2) * (k / (n / 2))) % n + 1
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  k -= 1
  p (k+n%2*k/(n/2))%n+1
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  if n.even?
    puts (k-1)%n+1
  else
    k%=n/2*n
    puts (k+(k-1)/(n/2)-1)%n+1
  end
end


One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?

The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.

Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).

n=gets.to_i
a=gets.split.map(&:to_i)
t=Hash.new()
t.default=0
a.each{|q| t[q]+=1 }
a.sort!
now,count=a[0],1
while count<n
        t[now]-=1
        #上があるなら使う
        if t[now+1]>0
                now+=1
        elsif t[now-1]>0
                now-=1
        else
                puts "NO"
                exit
        end
        count+=1
end
if (a[0]-now).abs==1
        puts "YES"
else
        puts "NO"
end


You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied:  The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string;  The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because:  the second half of the string ("aaaa") consists of only the character 'a';  the first half of the string ("cdbb") is 'b'-good string, because:   the second half of the string ("bb") consists of only the character 'b';  the first half of the string ("cd") is 'c'-good string, because:   the first half of the string ("c") consists of only the character 'c';  the second half of the string ("d") is 'd'-good string.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) — the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.

6
8
bbdcaaaa
8
asdfghjk
8
ceaaaabb
8
bbaaddcc
1
z
2
ac

def solve(s, c)
    return s != c ? 1 : 0 if s.size == 1
    m = s.size / 2
    l = m - s[m...s.size].count(c) + solve(s[0...m], c.succ)
    r = m - s[0...m].count(c) + solve(s[m...s.size], c.succ)
    [l, r].min
end
gets.to_i.times do
    n = gets.to_i
    s = gets.chomp
    puts solve(s, 'a')
end


According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE

The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.

Print a single number which is the number of people Vasya should check to guarantee the law enforcement.

NoteIn the sample test the second and fifth clients should be checked.

gets
p gets(p).split.select{|_|(%w(ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE)+[*?0.."17"]).include? _}.size

def toi(n)
  if n.to_i.to_s != n
    10000
  else
    n.to_i
  end
end

def check(str)
  alchohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]
  is_al = alchohol.find { |drink| str == drink }
  return true if (is_al)
  return toi(str) < 18
end

n = gets.chomp.to_i
s = 0
n.times do
  str = gets.chomp
  if check str
    s += 1
  end
end

puts s

a,ctr=[],0
al=["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]
n=gets.to_i
n.times do
	x=gets.chomp
	ctr+=1 if al.include?(x) || (x =~ /[0-9]+/ && x.to_i < 18)
end
puts ctr

n = gets.strip.to_i
drinks = [ "ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE" ]
ans = 0
n.times do
    i = gets.strip
    if i =~ /[0-9]/
        age = i.to_i
        ans += 1 if age < 18
    else
        ans += 1 if drinks.include? i
    end
end
puts ans

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
dr=[:ABSINTH, :BEER, :BRANDY, :CHAMPAGNE, :GIN, :RUM, :SAKE, :TEQUILA, :VODKA, :WHISKEY, :WINE].map{|v| v.to_s}

0.upto(17){|age|
	dr << age.to_s
}

count=0
n.times{
	line=gets.strip

	if dr.include?(line)
		count+=1
	end
}

puts count

judge_arr = %w(ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE)
s=gets
vcount=0
s.to_i.times {
  a=gets
  a.chop!
  if(a.match(/\d+/)==nil) then
    judge_arr.include?(a)?vcount+=1:vcount
  else
    a.to_i<18?vcount+=1:vcount
  end
  }
  puts vcount

drinks = ["ABSINTH","BEER","BRANDY","CHAMPAGNE","GIN","RUM","SAKE","TEQUILA", "VODKA","WHISKEY", "WINE"]
n = gets.to_i
count = 0
n.times do |i|
	line = gets.chomp.upcase

	age = line.to_i unless line =~ /[A-Z]/
	# puts line
	count += 1 if ((age && age < 18) || drinks.include?(line) )
	# puts "count #{count}"
end
puts count

n = gets.to_i

count = 0
mas = ",ABSINTH,BEER,BRANDY,CHAMPAGNE,GIN,RUM,SAKE,TEQUILA,VODKA,WHISKEY,WINE,"
for i in 0..n-1
  s = gets.chomp!
  if ((s =~ /[0-9]+/ && s.to_i < 18) || (mas.index(","+s+",") != nil))
    count += 1
  end
end

puts count

alcohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM",
           "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]

num = gets.chomp.to_i

count = 0

num.times do |i|
  str = gets.chomp
  if str =~ /\d+/
    if str.to_i < 18
      count = count + 1
    end
  else
    if alcohol.include? str
      count = count + 1
    end
  end
end

puts count

n = gets.chomp.to_i
guys = n.times.map { gets.chomp }

alc = %w(ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE)

cnt = 0
guys.each do |g|
  cnt += 1 if (g =~ /(\d+)/ && $1.to_i < 18) || alc.include?(g)
end

puts cnt

a,ctr=[],0
al=["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]
n=gets.to_i
n.times do
	x=gets.chomp
	ctr+=1 if al.include?(x) || (x.to_i!=0 && x.to_i<18)
end
puts ctr

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
dr=[:ABSINTH, :BEER, :BRANDY, :CHAMPAGNE, :GIN, :RUM, :SAKE, :TEQUILA, :VODKA, :WHISKEY, :WINE].map{|v| v.to_s}

count=0
n.times{
	line=gets.strip

	age=line.to_i
	age=19 if age==0

	if dr.include?(line) || age<18
		puts "line=#{line} age=#{age}"
		count+=1
	end
}

puts count

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
dr=[:ABSINTH, :BEER, :BRANDY, :CHAMPAGNE, :GIN, :RUM, :SAKE, :TEQUILA, :VODKA, :WHISKEY, :WINE].map{|v| v.to_s}

count=0
n.times{
	line=gets.strip

	age=line.to_i
	age=19 if age==0

	if dr.include?(line) || age<18
		count+=1
	end
}

puts count

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
dr=[:ABSINTH, :BEER, :BRANDY, :CHAMPAGNE, :GIN, :RUM, :SAKE, :TEQUILA, :VODKA, :WHISKEY, :WINE].map{|v| v.to_s}

0.upto(17){|age|
	puts age
	dr << age.to_s
}

count=0
n.times{
	line=gets.strip

	if dr.include?(line)
		count+=1
	end
}

puts count

#=================================
require 'prime'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.to_i
dr=[:ABSINTH, :BEER, :BRANDY, :CHAMPAGNE, :GIN, :RUM, :SAKE, :TEQUILA, :VODKA, :WHISKEY, :WINE].map{|v| v.to_s}

1.upto(17){|age|
	dr << age.to_s
}

count=0
n.times{
	line=gets.strip

	if dr.include?(line)
		count+=1
	end
}

puts count

drinks = ["ABSINTH","BEER","BRANDY","CHAMPAGNE","GIN","RUM","SAKE","TEQUILA", "VODKA","WHISKEY", "WINE"]
n = gets.to_i
count = 0
n.times do |i|
	line = gets.chomp
	age = line.to_i
	# puts line
	count += 1 if ((age > 0 && age < 18) || (age == 0 && drinks.include?(line)) )
	# puts "count #{count}"
end
puts count

n = gets.to_i

count = 0
mas = "ABSINTH,BEER,BRANDY,CHAMPAGNE,GIN,RUM,SAKE,TEQUILA,VODKA,WHISKEY,WINE"
for i in 0..n-1
  s = gets.chomp!
  if ((s =~ /[0-9]+/ && s.to_i < 18) || (mas.index(s) != nil))
    count += 1
  end
end

puts count


One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change.For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.

The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1.

Print a single string — the user's final name after all changes are applied to it.

NoteLet's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb".

class T
    def initialize(l, r)
        @l = l
        @r = r
        @m = (l + r) / 2
        @c = r - l
    end

    def l
        @pl = @pl || T.new(@l, @m)
    end

    def r
        @pr = @pr || T.new(@m, @r)
    end

    def c
        @c
    end

    def d(i)
        @c -= 1
        if @r - @l == 1
            @l
        elsif i < l.c
            l.d(i)
        else
            r.d(i - l.c)
        end
    end
end

r = gets.to_i
s = gets.chop
t = Array.new(128){T.new(0, r * s.size)}
d = Array.new(128){[]}
gets.to_i.times{|i|
    p, c = gets.split
    c = c.ord
    d[c] << t[c].d(p.to_i - 1)
}
d.each{|_|
    _.sort!.reverse!
}
t = [0] * 128
z = []
r.times{
    s.each_byte{|b|
        if t[b] == d[b][-1]
            d[b].pop
        else
            z << b
        end
        t[b] += 1
    }
}
puts z.map(&:chr) * ''

k = gets().to_i
s = gets().chomp
n = gets().to_i
changes = []
n.times { changes << gets().chomp.split }

name = s * k

letter_indexes = {}
0.upto(name.size - 1) do |i|
  letter = name[i]
  letter_indexes[letter] ||= []
  letter_indexes[letter] << i
end

changes.each do |position, letter|
  position = position.to_i

  if indexes = letter_indexes[letter] and indexes.size >= position
    name[indexes[position - 1]] = '0'
    letter_indexes[letter].delete_at(position - 1)
  end
end

puts name.delete('0')

# http://codeforces.ru/contest/159/problem/C

def run(input = STDIN.read)
  lines = input.split("\n")

  k = lines[0].to_i
  s = lines[1]
  n = lines[2].to_i

  cmd = lines[3..-1]

  word = (s * k)

  h = {}
  l = {}

  i = 0
  word.each_char { |c|
    if h.has_key?(c) then
      h[c].push(i)
    else
      h[c] = [i]
    end
    i += 1
  }

  #p h

  cmd.each { |c|
    (occurance, letter) = c.split(" ")
    occurance = occurance.to_i

    pos = h[letter][occurance - 1]
    word[pos] = "0"
    h[letter].delete_at(occurance - 1)

    #p word
  }

  return word.delete("0")
end

begin
  require './testingx.rb'
rescue LoadError
  puts run
end
__END__
2
bac
3
2 a
1 b
2 c
=
acb
---
1
abacaba
4
1 a
1 c
2 b
1 a
=
baa
---
3
derp
3
1 p
1 p
1 p
1 r
2 r
2 d
=
deerde
---
3
xxx
2
1 x
8 x
=
xxxxxxx
---
3
derp
2
2 p
1 p
1 d
2 d
=
erdererp

class T
    def initialize(l, r)
        @l = l
        @r = r
        @m = (l + r) / 2
        @c = r - l
    end

    def l
        @pl = @pl || T.new(@l, @m)
    end

    def r
        @pr = @pr || T.new(@m, @r)
    end

    def c
        @c
    end

    def d(i)
        @c -= 1
        if @r - @l == 1
            @l
        elsif i < l.c
            l.d(i)
        else
            r.d(i - l.c)
        end
    end
end

r = gets.to_i
s = gets.chop
t = Array.new(128){T.new(0, r * s.size)}
d = Array.new(128){[]}
gets.to_i.times{|i|
    p, c = gets.split
    c = c.ord
    d[c] << t[c].d(p.to_i - 1)
}
d.each{|_|
    _.sort!.reverse!
}
t = [0] * 128
z = []
r.times{
    s.each_byte{|b|
        if t[b] == d[b][-1]
            d[b].pop
        else
            t[b] += 1
            z << b
        end
    }
}
puts z.map(&:chr) * ''

k = gets().to_i
s = gets().chomp
name = s * k

letter_entries = {}

n = gets().to_i
n.times do
  change = gets().chomp.split
  entry = change[0].to_i
  letter = change[1]

  letter_entries[letter] ||= []
  letter_entries[letter] << entry
end

letter_entries.each do |letter, entries|
  entries.sort!

  1.upto(entries.size - 1) do |i|
    entries[i] += i
  end
end

name_letters = name.split('')
current_letter_entries = {}

0.upto(name_letters.size-1) do |i|
  letter = name_letters[i]

  current_letter_entries[letter] ||= 0
  current_letter_entries[letter] += 1

  name_letters[i] = nil if letter_entries[letter].include?(current_letter_entries[letter])
end

puts name_letters.compact.join

class String
  def char_distr
    split('').inject({}) { |hash, e| hash[e] ||= 0; hash[e] += 1; hash }
  end

  def delete_nth_entry(letter, entry)
    index = 0

    while entry > 0
      entry -= 1 if self[index] == letter
      index += 1
    end

    self[index-1] = ''
    self
  end
end

def find_piece_and_index(letter, entry, char_distributions)
  index = 0
  sum = char_distributions[index][letter]
  prev_sum = 0
  while entry > sum && index < char_distributions.size
    index += 1
    prev_sum = sum
    sum += char_distributions[index][letter]
  end
  return index, (entry - prev_sum)
end

k = gets().to_i
s = gets().chomp
pieces = []
k.times { pieces << s.dup }

char_distribution = s.char_distr
char_distributions = []
k.times { char_distributions << char_distribution.dup }

n = gets().to_i
n.times do
  change = gets().split
  entry = change[0].to_i
  letter = change[1]

  piece, local_entry = find_piece_and_index(letter, entry, char_distributions)
  pieces[piece].delete_nth_entry(letter, local_entry)
  char_distributions[piece][letter] -= 1
end

p pieces.join('')

k = gets().to_i
s = gets().chomp
name = s * k

letter_entries = {}

n = gets().to_i
n.times do
  change = gets().chomp.split
  entry = change[0].to_i
  letter = change[1]

  letter_entries[letter] ||= []
  letter_entries[letter] << entry
end

letter_entries.each do |letter, entries|
  old_value = entries[0]
  1.upto(entries.size - 1) do |i|
    entries[i] += i if entries[i] >= old_value
  end
end

name_letters = name.split('')
current_letter_entries = {}

0.upto(name_letters.size-1) do |i|
  letter = name_letters[i]

  current_letter_entries[letter] ||= 0
  current_letter_entries[letter] += 1

  if letter_entries[letter] && letter_entries[letter].include?(current_letter_entries[letter])
    name_letters[i] = nil
  end
end

puts name_letters.compact.join

k = gets().to_i
s = gets().chomp
name = s * k

letter_entries = {}

n = gets().to_i
n.times do
  change = gets().chomp.split
  entry = change[0].to_i
  letter = change[1]

  letter_entries[letter] ||= []
  letter_entries[letter] << entry
end

letter_entries.each do |letter, entries|
  entries.sort!

  1.upto(entries.size - 1) do |i|
    entries[i] += i
  end
end

name_letters = name.split('')
current_letter_entries = {}

0.upto(name_letters.size-1) do |i|
  letter = name_letters[i]

  current_letter_entries[letter] ||= 0
  current_letter_entries[letter] += 1

  if letter_entries[letter] && letter_entries[letter].include?(current_letter_entries[letter])
    name_letters[i] = nil
  end
end

puts name_letters.compact.join

class String
  def delete_nth_entries!(letter, entries)
    index = 0
    entry_index = 0
    current_entry = 0

    while entry_index < entries.size
      if self[index] == letter
        current_entry += 1
        if current_entry == entries[entry_index]
          self[index] = ''
          entry_index += 1
        end
      end
      index += 1
    end

    self
  end
end

k = gets().to_i
s = gets().chomp
name = s * k

letter_entries = {}

n = gets().to_i
n.times do
  change = gets().chomp.split
  entry = change[0].to_i
  letter = change[1]

  letter_entries[letter] ||= []
  letter_entries[letter] << entry
end

letter_entries.each do |letter, entries|
  entries.sort!

  1.upto(entries.size - 1) do |i|
    entries[i] += i
  end
  p letter_entries
  p name
  name.delete_nth_entries!(letter, entries)
end

puts name

# http://codeforces.ru/contest/159/problem/C

def run(input = STDIN.read)
  lines = input.split("\n")

  k = lines[0].to_i
  s = lines[1]
  n = lines[2].to_i

  cmd = lines[3..-1]

  word = (s * k)

  h = {}
  l = {}

  i = 0
  word.each_char { |c|
    if h.has_key?(c) then
      h[c].push(i)
    else
      h[c] = [i]
    end
    i += 1
  }

  cmd.each { |c|
    (occurance, letter) = c.split(" ")
    occurance = occurance.to_i

    while (pos = h[letter][occurance - 1]) == nil
      occurance += 1
    end

    word[pos] = "0"
    h[letter][occurance - 1] = nil
  }

  return word.delete("0")
end

begin
  require './testing.rb'
rescue LoadError
  puts run
end
__END__
2
bac
3
2 a
1 b
2 c
=
acb
---
1
abacaba
4
1 a
1 c
2 b
1 a
=
baa
---
3
derp
2
1 p
1 p
1 p
2 r
2 r
1 r
2 d
=
deede


...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.

The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ ). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.

Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.

NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).A rooted tree is a tree where one vertex is selected to be the root.

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

sm = [];
n.times do |i| sm[i] = [] end

m.times do
    a,b = gets.split(' ').map(&:to_i)
    a -= 1
    b -= 1
    sm[a][b] = 1
end

p = []
$q = 0
def rec(id,p,sm,n)
    p[id] |= 0
    if p[id] == 1 then return end
    p[id] = 1
    $q += 1
    n.times do |i|
        sm[id][i] |= 0
        if sm[id][i] == 1 or sm[i][id] == 1 then
            rec(i,p,sm,n)
        end
    end
end

rec(0,p,sm,n)
if($q == n and $q == m) then puts('FHTAGN!');
else puts('NO');
end

$n,$m=gets.split.map &:to_i
$e=Array.new($n+1){[]}
$m.times{a,b=gets.split.map &:to_i;$e[a]<<b;$e[b]<<a}
$visited=[]
def dfs(pos)
	$visited<<pos
	($e[pos]-$visited).each{|_pos|return true if dfs(_pos)}
	$visited.uniq!
	return $visited.size==$n ? true : false
end
puts $n>2&&$n==$m&&dfs(1) ? "FHTAGN!" : "NO"

$n,$m=gets.split.map &:to_i
$e=Array.new($n+1){[]}
$m.times{a,b=gets.split.map &:to_i;$e[a]<<b;$e[b]<<a}
$visited=[]
def dfs(pos)
	$visited<<pos
	($e[pos]-$visited).each{|_pos|return true if dfs(_pos)}
	return $visited.size==$n ? true : false
end
puts $n>2&&$n==$m&&dfs(1) ? "FHTAGN!" : "NO"

$n,$m=gets.split.map &:to_i
$e=Array.new($n+1){[]}
$m.times{a,b=gets.split.map &:to_i;$e[a]<<b;$e[b]<<a}
$visited=[]
def dfs(pos)
	$visited<<pos
	($e[pos]-$visited).each{|_pos|return true if dfs(_pos)}
	return $visited.size==$n ? true : false
end
puts $n==$m&&dfs(1) ? "FHTAGN!" : "NO"

n,m=gets.split.map &:to_i
puts n==m ? "FHTAGN!" : "NO"


Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \times 2$$$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid.  Additional constraint on the input: each input corresponds to at least one valid tiling.

For each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any.

NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like:   In the second test case, Alice shows Bob the bottom row, the whole grid may look like:   In the third test case, Alice shows Bob the bottom row, the whole grid may look like:   In the fourth test case, Alice shows Bob the top row, the whole grid may look like:

t = gets.to_i

t.times do

n = gets.to_i
s = gets.chomp

puts s.tr("UD", "DU")

end


After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s.Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response.

In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10).  Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive.

Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any.

Go_straight_along_this_street
5
str
long
tree
biginteger
ellipse

NoteIn the first sample, the solution is traight_alon.In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on.In the third sample, the solution is either nagio or oisii.

s = gets.chomp
n = gets.to_i
words = []
n.times do
  words << gets.chomp
end

len = s.size
r = []
words.each do |w|
  r2 = []
  idx = 0
  pos = 0
  while p2 = s.index(w, pos)
    r2 << [pos, p2+w.size-1] if p2 == 0 || pos < p2

    pos = p2 + 1
  end
  r2 << [pos, len]

  #p r2.map{|a,b| [a, b, s[a..b-1]]}
  r << r2
end

elms = r.map{|v|v.shift}

result = [0, 0]
while true
  #p elms
  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][0] < a }
  aa = elms[idx][0]

  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][1] > b }
  bb = elms[idx][1]
  #p [bb-aa, aa, s[aa..bb-1], idx]

  result = [bb-aa, aa] if bb-aa > result[0]

  break if r[idx].empty?
  elms[idx] = r[idx].shift
end
#p result
puts result*" "

s = gets.chomp
n = gets.to_i
words = []
n.times do
  words << gets.chomp
end

len = s.size
r = []
words.each do |w|
  r2 = []
  idx = 0
  pos = 0
  while p2 = s.index(w, pos)
    r2 << [pos, p2+w.size-1] if pos > p2

    pos = p2 + 1
  end
  r2 << [pos, len]

  #p r2.map{|a,b| [a, b, s[a..b-1]]}
  r << r2
end

elms = r.map{|v|v.shift}

result = [0, 0]
while true
  #p elms
  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][0] < a }
  aa = elms[idx][0]

  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][1] > b }
  bb = elms[idx][1]
  #p [bb-aa, aa, s[aa..bb-1], idx]

  result = [bb-aa, aa] if bb-aa > result[0]

  break if r[idx].empty?
  elms[idx] = r[idx].shift
end
#p result
puts result*" "

s = gets.chomp
n = gets.to_i
words = []
n.times do
  words << gets.chomp
end

len = s.size
r = []
words.each do |w|
  r2 = []
  idx = 0
  pos = 0
  while p2 = s.index(w, pos)
    r2 << [pos, p2+w.size-1] if pos < p2

    pos = p2 + 1
  end
  r2 << [pos, len]

  #p r2.map{|a,b| [a, b, s[a..b-1]]}
  r << r2
end

elms = r.map{|v|v.shift}

result = [0, 0]
while true
  #p elms
  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][0] < a }
  aa = elms[idx][0]

  idx = 0
  elms.each_with_index{|(a,b),i| idx = i if elms[idx][1] > b }
  bb = elms[idx][1]
  #p [bb-aa, aa, s[aa..bb-1], idx]

  result = [bb-aa, aa] if bb-aa > result[0]

  break if r[idx].empty?
  elms[idx] = r[idx].shift
end
#p result
puts result*" "


One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2·n arcs.For example, if the numbers are written in the circle in the order 1, 2, 3, 4, 5 (in the clockwise direction), then the arcs will join pairs of integers (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3), (2, 4), (3, 5), (4, 1) and (5, 2).Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2·n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.

The first line of the input contains a single integer n (5 ≤ n ≤ 105) that shows, how many numbers were written on the board. Next 2·n lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers that were connected by the arcs. It is guaranteed that no pair of integers, connected by a arc, occurs in the input more than once. The pairs of numbers and the numbers in the pairs are given in the arbitrary order.

If Vasya made a mistake somewhere and there isn't any way to place numbers from 1 to n on the circle according to the statement, then print a single number "-1" (without the quotes). Otherwise, print any suitable sequence of n distinct integers from 1 to n.  If there are multiple solutions, you are allowed to print any of them. Specifically, it doesn't matter which number you write first to describe the sequence of the order. It also doesn't matter whether you write out the numbers in the clockwise or counter-clockwise direction.

def check ans
  used=[false]*$n
  ans.each {|i| used[i]=true}
  (3...$n).each {|i|
    $a[ans[i-1]].each {|j|
      if !used[j] && $a[j].include?(ans[i-2])
        ans<<j
        used[j]=true
        break
      end
    }
    return false if !ans[i]
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Array.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a.each {|i|
  if i.size!=4
    puts -1
    exit
  end
}

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j) && ($a[i] & $a[j]).size>=2
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
arcs = []
(2*n).times do
	arc = STDIN.readline.split.collect {|s| s.to_i }
	arcs.push(arc.sort)
end

if n <= 6
	order = (1..n).collect {|x| x }
	k = order.length
	order.permutation.each do |p|
		okay = true
		k.times do |i|
			next1 = [p[i], p[(i+1)%k]]
			okay = false if !arcs.include?(next1.sort)
			next2 = [p[i], p[(i+2)%k]]
			okay = false if !arcs.include?(next2.sort)
			prev1 = [p[i], p[(i+k-1)%k]]
			okay = false if !arcs.include?(prev1.sort)
			prev2 = [p[i], p[(i+k-2)%k]]
			okay = false if !arcs.include?(prev2.sort)
			break if !okay
		end
		if okay
			puts p.join(' ')
			exit
		end
	end
end

h, seen = [nil], [nil]
n.times do
	h.push([])
	seen.push(false)
end
arcs.each do |a, b|
	h[a].push(b)
	h[b].push(a)
end
(1..n).each {|v| h[v].sort! }

def count_matches(arr, brr)
	count = 0
	i, j = 0, 0
	while true
		if arr[i] == brr[j]
			count += 1
			i += 1
			j += 1
			break if arr[i] == nil or brr[j] == nil
		elsif arr[i] < brr[j]
			i += 1
			break if arr[i] == nil
		else
			j += 1
			break if brr[j] == nil
		end
	end
	return count
end

order = []
v = 1
n.times do
	neighbors = h[v]
	w = -1
	neighbors.each do |neighbor|
		if seen[neighbor]
			next if (order.length != n-1 || neighbor != order[0])
		end
		if count_matches(neighbors, h[neighbor]) == 2
			w = neighbor
			break
		end
	end
	if (w == -1)
		puts -1
		exit
	end
	seen[v] = true
	order.push(v)
	v = w
end

puts order.join(' ')

BEGIN{
  def gint()
    return gets.split.map(&:to_i)
  end
  def solve(ans, graph, n)
    isin = [false] * (n + 1)
    ans.each do |item|
      isin[item] = true
    end
    flag = true
    while ans.length < n and flag do
      flag = false
      u = ans[-1]
      v = ans[-2]
      graph[u].each do |itemu|
        break if flag
        if not isin[itemu] then
          graph[v].each do |itemv|
            if itemu == itemv and \
              not isin[itemv] then
              ans << itemu
              isin[itemu] = true
              flag = true
              break
            end
          end
        end
      end
    end
    return flag
  end
  def main()
    n = gint[0]
    graph = []
    (n + 1).times do |i|
      graph << []
    end
    gg = false
    (n * 2).times do |i|
      a, b = gint
      graph[a] << b
      graph[b] << a
      gg = true if graph[a].length == 5 || graph[b].length == 5
    end
    flag = false
    ans = 0
    gg = true if graph[1].length != 4
    if not gg then
      graph[1].each do |item1|
        break if flag
        graph[1].each do |item2|
          if item1 != item2 then
            ans = [1]
            ans << item1 << item2
            flag = solve(ans, graph, n)
            break if flag
          end
        end
      end
    end
    if gg or !flag then
      puts -1
    else
      ans.each do |item|
        print item,' '
      end
      puts
    end
  end
  Test_case = 1
  Test_case.times do
    main()
  end
}

require 'set'

def check ans
  (1...$n).each {|i|
    common=($a[ans[i]]-[ans[i-1],ans[(i+1)%$n]]) & $a[ans[(i+1)%$n]]
    return false if not common
    if i+2<$n
      ans<<common.first
    end
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j)
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  used=[false]*$n
  ans.each {|i| used[i]=true}
  (3...$n).each {|i|
    $a[ans[i-1]].each {|j|
      if !used[j] && $a[j].include?(ans[i-2])
        ans[i]=j
        used[j]=true
        break
      end
    }
    return false if ans[i]==0
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a.each {|i|
  if i.size!=4
    puts -1
    exit
  end
}
$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j) && ($a[i] & $a[j]).size>2
      ans=[0]*$n
      ans[1]=i
      ans[2]=j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  (1...$n-1).each {|i|
    common=($a[ans[i]]-[ans[i-1],ans[(i+1)%$n]]) & $a[ans[(i+1)%$n]]
    return false if common.size==0

    if i+2<$n
      return false if common.size==0
      ans<<common.first
    end
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
  if $a[input[0]].length>4 || $a[input[1]].length>4
    puts -1
    exit
  end
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j)
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

def check ans
  used=[false]*$n
  ans.each {|i| used[i]=true}
  (3...$n).each {|i|
    $a[ans[i-1]].each {|j|
      if !used[j] && $a[j].include?(ans[i-2])
        ans<<j
        used[j]=true
        break
      end
    }
    return false if !ans[i]
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Array.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j) && ($a[i] & $a[j]).size>=2
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  used=[false]*$n
  ans.each {|i| used[i]=true}
  (3...$n).each {|i|
    $a[ans[i-1]].each {|j|
      if !used[j] && $a[j].include?(ans[i-2])
        ans[i]=j
        used[j]=true
        break
      end
    }
    return false if !used[i]
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a.each {|i|
  if i.size!=4
    puts -1
    exit
  end
}
$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j) && (($a[i]-[0]) & ($a[j]-[0])).size>0
      ans=[0]*$n
      ans[1]=i
      ans[2]=j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  used=[false]*$n
  3.times {|i| used[i]=true}
  (3...$n).each {|i|
    $a[ans[i-1]].each {|j|
      if !used[j] && $a[j].include?(ans[i-2])
        ans[i]=j
        used[j]=true
        break
      end
    }
    return false if ans[i]==0
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j) && ($a[i] & $a[j]).size>=2
      ans=[0]*$n
      ans[1]=i
      ans[2]=j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  (1...$n-1).each {|i|
    common=($a[ans[i]]-[ans[i-1],ans[(i+1)%$n]]) & $a[ans[(i+1)%$n]]
    return false if common.size==0

    if i+2<$n
      common-=ans
      return false if common.size!=1
      ans<<common.first
    end
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
  if $a[input[0]].length>4 || $a[input[1]].length>4
    puts -1
    exit
  end
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j)
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  (1...$n).each {|i|
    common=($a[ans[i]]-[ans[i-1],ans[(i+1)%$n]]) & $a[ans[(i+1)%$n]]
    return false if not common
    common-=ans
    return false if common.length==0
    if i+2<$n
      ans<<common.first
    end
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j)
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

require 'set'

def check ans
  (1...$n-1).each {|i|
    common=($a[ans[i]]-[ans[i-1],ans[(i+1)%$n]]) & $a[ans[(i+1)%$n]]
    return false if common.size==0
    common=common.to_a
    if i+2<$n
      if ans.include? common.first
        ans<<common.last
      else
        ans<<common.first
      end
    end
  }
  true
end

$n=gets.to_i
$a=Array.new($n) {Set.new}

($n*2).times do
  input=gets.split.map{|i| i.to_i-1}
  $a[input[0]]<<input[1]
  $a[input[1]]<<input[0]
  if $a[input[0]].length>4 || $a[input[1]].length>4
    puts -1
    exit
  end
end

$a[0].each {|i|
  $a[0].each {|j|
    if i!=j && $a[i].include?(j)
      ans=[0]
      ans<<i
      ans<<j
      if check ans
        ans.each {|k| print (k+1).to_s + ' '}
        exit
      end
    end
  }
}

puts -1

BEGIN{
	def gint()
		return gets.split.map(&:to_i)
	end
	def main()
		n = gint[0]
		(n * 2).times do |i|
			a, b = gint
		end
		if n == 5 then
			print "1 2 3 4 5\n"
		elsif n == 6 then
			print "1 3 6 5 2 4\n"
		else
			print "1 2 3 4 5\n"
		end
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}


There are three cells on an infinite 2-dimensional grid, labeled $$$A$$$, $$$B$$$, and $$$F$$$. Find the length of the shortest path from $$$A$$$ to $$$B$$$ if:   in one move you can go to any of the four adjacent cells sharing a side;  visiting the cell $$$F$$$ is forbidden (it is an obstacle).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first one contains two integers $$$x_A, y_A$$$ ($$$1 \le x_A, y_A \le 1000$$$) — coordinates of the start cell $$$A$$$. The second one contains two integers $$$x_B, y_B$$$ ($$$1 \le x_B, y_B \le 1000$$$) — coordinates of the finish cell $$$B$$$. The third one contains two integers $$$x_F, y_F$$$ ($$$1 \le x_F, y_F \le 1000$$$) — coordinates of the forbidden cell $$$F$$$. All cells are distinct. Coordinate $$$x$$$ corresponds to the column number and coordinate $$$y$$$ corresponds to the row number (see the pictures below).

Output $$$t$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th test case: the length of the shortest path from the cell $$$A$$$ to the cell $$$B$$$ if the cell $$$F$$$ is not allowed to be visited.

Note    An example of a possible shortest path for the first test case.     An example of a possible shortest path for the second test case.

def incl(a, b, f, i)
  a = a[i]
  b = b[i]
  a, b = b, a if b < a
  (a..b).include?(f[i])
end

gets.to_i.times {
  gets
  a = gets.split.map!(&:to_i)
  b = gets.split.map!(&:to_i)
  f = gets.split.map!(&:to_i)
  x = a.zip(b).map { (_1 - _2).abs }

  ans = x.sum
  ans += 2 if x[0] == 0 && a[0] == f[0] && incl(a, b, f, 1)
  ans += 2 if x[1] == 0 && a[1] == f[1] && incl(a, b, f, 0)

  p ans
}