According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.

The first line of the input contains numbers n and m (1 ≤ n, m ≤ 100), n — the amount of rows, m — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.

Output YES, if the flag meets the new ISO standard, and NO otherwise.

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

t = Array.new(m) {|i| i = []}
result = "YES"

n.times do
    s = gets.chomp
    k = s[0]
    if s.delete(s[0]).size != 0 then
        result = "NO"
    end
    m.times do |i|
        if t[i][-1] == s[i] then
            result = "NO"
        end
        t[i] << s[i]
    end
end

puts result

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

ret = "YES"
for i in 0..n-1
	for j in 1..m-1
		if ar[i][j] != ar[i][0]
			ret = "NO"
			break;
		end
	end
	if i > 0
		if ar[i][0] == ar[i-1][0]
			ret = "NO"
			break;
		end
	end
end

puts ret

n, m = gets.strip.split.map { |e| e.to_i }
color = ''
bool = true
n.times do
	str = gets.strip.squeeze
	if str.size != 1
		bool = false
	else
		if str != color
			color = str
		else
			bool = false
		end
	end
end
if bool
	puts 'YES'
else
	puts 'NO'
end

n=gets.to_i
back=-1
(1..n).each{
        data=gets.split[0]
        if(back==data[0].to_i) then
                puts "NO"
                exit
        end
        back=data[0].to_i
        for i in 1..data.length-1
                if(data[i].to_i!=data[0].to_i) then
                        puts "NO"
                        exit
                end
        end
}
puts "YES"

n=gets.to_i
a=gets(p).split.map(&:squeeze)
puts a.all?{|s|s.size<2}&&(a*"").squeeze.size==n ?:YES :"NO"

#!/usr/bin/ruby

n, m = gets.chomp.split.map{|e| e.to_i}
color = -1
n.times do
  this_line = gets.chomp.split('').map{|e| e.to_i}
  if this_line[0] == color
    puts "NO"
    exit
  end
  color = this_line[0]
  this_line.each{|e|
    if e != color
      puts "NO"
      exit
    end
  }
end
puts "YES"

rez = gets.split(" ").map { |e| e.to_i }
flag = true
k = 0
ch = 'a'
rez[0].times {
    s = gets
    k += 1
    if k != 1
        if s[0] == ch then
            flag = false
            break
        end
    end
    mas = s.chomp.split("").map { |e| e.to_i }
    mas = mas | mas
    if mas.size != 1
        flag = false
    end
    ch = s[0]

}
puts "YES" if flag
puts "NO" if !flag

n, m = gets.split.map(&:to_i)
grid = []
compare = [""]
iso = false
n.times do
	row = gets.chomp.split('')
	unique = row.uniq
	if unique.length > 1 || unique == compare
		puts "NO"
		iso = false
	else
		compare = unique
		iso = true
	end
	break unless iso
end
puts "YES" if iso

def main()
	nm=gets.chomp.to_s.split(" ");
	n=nm[0].to_i;
	m=nm[1].to_i;
	fr=gets.chomp;
	prevn=fr[0].chr;
	nofn=fr.count(prevn);
	if nofn==m
		f=true;
		for i in 1...n
			r=gets.chomp;
			if prevn==r[0].chr
				f=false;
			else
				prevn=r[0].chr;
				nofn=r.count(prevn);
				if nofn!=m
					f=false;
				end
			end
		end
		if f
			puts "YES"
		else
			puts "NO"
		end
	else
		puts "NO";
	end
end
main()

input = gets.chomp.split(' ').map { |e| e.to_i }
flag = Array.new(input[1])
f_bool = true
(0...input[0]).each do |i|
  flag[i] =  gets.chomp.to_s
end
(0...input[0]).each do |i|
   if flag[i].count(flag[i][0]) != flag[i].length
     puts "NO"
     f_bool = false
     break
  else
      if flag.length == 1
       puts "YES"
       f_bool = false
       break
     else
       if i == 0
         if flag[0] == flag[1]
           puts "NO"
           f_bool = false
           break
         end
       else
         if flag[i] == flag[i+1] || flag[i] == flag[i-1]
           puts "NO"
           f_bool = false
           break
         end
       end
     end
  end
end
puts "YES" if f_bool

n=gets.to_i
rows=gets(p).split.map(&:squeeze)
puts rows.all?{|str| str.size==1}&&(rows*"").squeeze.size==n ?:YES :"NO"

n, m = gets.split.collect{|i| i.to_i}
flag = Array.new(m,-1)
(1..n).each do
    tmp = gets.chomp.split("").collect{|i| i.to_i}
    if flag[0] == tmp[0] or tmp.count(tmp[0]) != m
        puts "NO"
        exit
    end
    flag = tmp
end
puts "YES"

n, m = gets.split.collect{|i| i.to_i}
flag = -1
(1..n).each do
    tmp = gets.chomp.split("").collect{|i| i.to_i}
    if flag == tmp[0] or tmp.count(tmp[0]) != m
        puts "NO"
        exit
    end
    flag = tmp[0]
end
puts "YES"

n_and_m = gets.split(" ")
n = n_and_m[0].to_i
m = n_and_m[1]
bandeira = []
resposta = "YES"
n.times do
	linha = gets.strip
	linha_horizontal = linha.split("")
	cor_da_linha = linha_horizontal.uniq
		if cor_da_linha.size != 1
			resposta = "NO"
		end
	bandeira << cor_da_linha
end
for cor in 1..bandeira.size - 1 do
	break if resposta == "NO" || bandeira.size == 1
	if bandeira[cor - 1] == bandeira[cor] || bandeira[cor + 1] == bandeira[cor]
		resposta = "NO"
		break
	else
		resposta = "YES"
	end
end
puts resposta

class String
  def uniq?
    self.split('').uniq.size < 2
  end
end

def print_no
  puts 'NO'
  exit
end

n, _ = gets.split.map { |x| x.to_i }
p = gets.chomp
print_no unless p.uniq?
for __ in 2..n
  s = gets.chomp
  print_no unless s != p && s.uniq?
  p = s
end
puts 'YES'

s1 = gets.chomp.split

n = s1[0].to_i
m = s1[1].to_i
k = 0
all = []
ok = true;

for i in 1..n do
	s = gets.chomp
	t = s[0];
	ok = true;
	for j in 1..s.length-1 do
		if t != s[j]
			ok = false;
		end
	end
	if not ok
		print "NO"
		break
	end
	all[k] = t
	k+=1
end

if ok
	tr = true
	for i in 0..k-2 do
		if all[i] == all[i + 1]
			print "NO"
			tr = false
			break
		end
	end

	if tr
		print "YES"
	end
end

n,m=gets.split.map(&:to_i)
prev="z"; result=true
n.times do
	line=gets.split(//)
	if line[0]==prev
		result=false
	end
	prev=line[0]
	if line.count(line[0])!=m
		result=false
	end
end

if result
	puts "YES\n"
else
	puts "NO\n"
end

gets; flag = STDIN.read.split "\n"

flag.each.with_index do |f, i|
	if f.length == f.count(f[0])
		f.length.times do |j|
			if i > 0
				(print :NO; exit) if flag[i][j] == flag[i - 1][j]
			end
		end
	else
		print :NO
		exit
	end
end

print :YES

t = gets.split.collect{|x| x.to_i}
n,m = t[0], t[1]

ok = 'YES'
last = ''

n.times do |i|
	s = gets.strip
	if last != ''
		if s == last
			ok = 'NO'
		end
	end
	if s != s[0]*m
		ok = 'NO'
	end
	last = s
end

puts ok

puts %w[YES NO][STDIN.readlines.drop(1).map { |x| x.chomp }.reduce(['*', 0]) { |s, x| [x[0], s.last | (x.chars.to_a.uniq.length == 1 && x[0] != s.first ? 0 : 1)] }.last]

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

t = {}
result = "YES"

n.times do
    s = gets.chomp
    k = s[0]
    if s.delete(s[0]).size != 0 then
        result = "NO"
    end
    m.times do |i|
        if t[i] then
            if t[i].include? s[i] then
                result = "NO"
            else
                t[i] << s[i]
            end
        else
            t[i] = [s[i]]
        end
    end
end

puts result

n_m = gets.chomp.split(' ').map { |i| i.to_i }
flag = Array.new(n_m[1])
(0...n_m[0]).each do |i|
  flag[i] = gets.chomp.to_s
end
bol = true
(0...n_m[1]).each do |i|
  if n_m[0] > 1
    if i == 0
      if flag[i] == flag[i+1]
        bol = false
        puts "NO"
        break
      end
      (0...flag[i].length).each do |j|
        if flag[i][0] != flag[i][j]
          bol = false
          puts "NO"
          break
        end
      end
      if bol == false
        break
      end
    else
      if flag[i] == flag[i+1] || flag[i] == flag[i-1]
        bol = false
        puts "NO"
        break
      end
      if bol == false
        break
      end
      (0...flag[i].length).each do |j|
        if flag[i][0] != flag[i][j]
          bol = false
          puts "NO"
          break
        end
      end
      if bol == false
        break
      end
    end
  else
    (0...n_m[1]).each do |j|
      if flag[0][0] != flag[0][j]
        bol = false
        puts "NO"
        break
      end
    end
    break if bol == false
  end
end
puts "YES" if bol == true

n_m = gets.chomp.split(' ').map { |i| i.to_i }
flag = Array.new(n_m[1])
(0...n_m[0]).each do |i|
  flag[i] = gets.chomp.to_s
end
bol = true
(0...n_m[1]).each do |i|
  if i== 0
    if flag[i] == flag[i+1]
      bol = false
      puts "NO"
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
  else
    if flag[i] == flag[i+1] || flag[i] == flag[i-1]
      bol = false
      puts "NO"
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
  end
end
puts "YES" if bol == true

input = gets.chomp.split(' ').map { |e| e.to_i }
flag = Array.new(input[1])
f_bool = true
(0...input[0]).each do |i|
  flag[i] =  gets.chomp.to_s
end
(0...input[0]).each do |i|
   if flag[i].count(flag[i][0]) != flag[i].length
     puts "NO"
     f_bool = false
  else
      if flag.length == 1
       puts "YES"
       f_bool = false
       break
     else
       if i == 0
         if flag[0] == flag[1]
           puts "NO"
           f_bool = false
           break
         end
       else
         if flag[i] == flag[i+1] || flag[i] == flag[i-1]
           puts "NO"
           f_bool = false
           break
         end
       end
     end
  end
end
puts "YES" if f_bool

n_m = gets.chomp.split(' ').map { |i| i.to_i }
flag = Array.new(n_m[1])
(0...n_m[0]).each do |i|
  flag[i] = gets.chomp.to_s
end
bol = true
(0...n_m[1]).each do |i|
  if i== 0
    if flag[i] == flag[i+1]
      bol = false
      puts "NO"
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
    if bol == false
      break
    end
  else
    if flag[i] == flag[i+1] || flag[i] == flag[i-1]
      bol = false
      puts "NO"
      break
    end
    if bol == false
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
    if bol == false
      break
    end
  end
end
puts "YES" if bol == true

n_m = gets.chomp.split(' ').map { |i| i.to_i }
flag = Array.new(n_m[1])
(0...n_m[0]).each do |i|
  flag[i] = gets.chomp.to_s
end
bol = true
(0...n_m[1]).each do |i|
  if n_m[0] == 1
    break
  end
  if i== 0
    if flag[i] == flag[i+1]
      bol = false
      puts "NO"
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
    if bol == false
      break
    end
  else
    if flag[i] == flag[i+1] || flag[i] == flag[i-1]
      bol = false
      puts "NO"
      break
    end
    if bol == false
      break
    end
    (0...flag[i].length).each do |j|
      if flag[i][0] != flag[i][j]
        bol = false
        puts "NO"
        break
      end
    end
    if bol == false
      break
    end
  end
end
puts "YES" if bol == true

n_and_m = gets.split(" ")
n = n_and_m[0].to_i
m = n_and_m[1]
bandeira = []
resposta = ""
n.times do
	linha = gets.strip
	linha_horizontal = linha.split("")
	cor_da_linha = linha_horizontal.uniq
		if cor_da_linha.size != 1
			resposta = "NO"
		end
	bandeira << cor_da_linha
end
for cor in 1..bandeira.size - 1 do
	break if resposta == "NO"
	if bandeira[cor - 1] == bandeira[cor] || bandeira[cor + 1] == bandeira[cor]
		resposta = "NO"
		break
	else
		resposta = "YES"
	end
end
puts resposta

t = gets.split.collect{|x| x.to_i}
n,m = t[0], t[1]

ok = 'YES'
last = ''

n.times do |i|
	s = gets.strip
	if last != ''
		if s == last or s != s[0]*m
			ok = 'NO'
		end
	else
		last = s
	end
end

puts ok

t = gets.split.collect{|x| x.to_i}
n,m = t[0], t[1]

ok = 'YES'
last = ''

n.times do |i|
	s = gets.strip
	if last != ''
		if s == last or s != s[0]*m
			ok = 'NO'
		end
	end
	last = s
end

puts ok


Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.

The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).

Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.


You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$.

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

Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element.

NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$.

def solve
    n = gets.strip.to_i
    a = gets.strip.split(' ').map(&:to_i)
    dp = Array.new(n + 1){ Array.new(3) }
    a.each_with_index { |e, i| dp[i][0] = dp[i][1] = dp[i][2] = 1 }
    an = -1
    a.each_with_index { |e, i|
        next if i == 0
        if i > 1
            dp[i][0] = dp[i - 2][1] + 1 if a[i] - a[i - 2] > 0
        end
        if a[i] - a[i - 1] > 0
            dp[i][1] = dp[i - 1][1] + 1
            dp[i][2] = [dp[i - 1][2], dp[i - 1][0]].max + 1
        end
        an = [an, dp[i][0], dp[i][2]].max
    }
    puts an
end

solve

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

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

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

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

i=0
cnt=0
prev=-1
while i<n do
  if prev < a[i]
    cnt+=1
  else
    # ng
    ans<<[i-cnt,i-1,cnt] if cnt>0
    cnt=1
  end
  prev=a[i]
  i+=1
end
ans<<[n-cnt,n-1,cnt] if cnt>0
#puts ans.to_s

prev_en=-2
prev_cnt=0
max=0
ans.each do |st,en,cnt|
  if (st-prev_en)==2 && a[prev_en]<a[st]
    c=cnt+prev_cnt
    max=c if max<c
  elsif (st-prev_en)==1 &&((cnt>1&&a[prev_en]<a[st+1]) || (prev_cnt>1&&a[prev_en-1]<a[st]))
    c=cnt+prev_cnt-1
    max=c if max<c
  end
  prev_en=en
  prev_cnt=cnt
  #puts max
end

max_unit = ans.map{|i|i[2]}.max

puts max(max,max_unit)


In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.Your program should handle the queries of the following two types:  "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.

The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct.

For each query of the second type print "YES" or "NO" on a separate line depending on the answer.

#!/usr/bin/ruby

$arr = []

def forward_edge(a, b, c, d)
	(c < a and a < d) or (c < b and b < d)
end

def dfs(vis, a)
	if vis[a]
		return
	end
	vis[a] = true

	(0...$arr.size).each do |u|
		if forward_edge(*$arr[a], *$arr[u])
			dfs(vis, u)
		end
	end
end

# a, b are 0-indexed
def query(a, b)
	vis = [false]*($arr.size)
	dfs(vis, a)

	puts vis[b] ? "YES" : "NO"
end

gets
readlines.each do |line|
	cmd, x, y = line.strip.split.map(&:to_i)
	if cmd == 1
		$arr << [x, y]
	else
		query(x - 1, y - 1)
	end
end

#!/usr/bin/env ruby
def can_go?(x, y, path, vis)
  vis[x] = true
  return true if x == y
  path[x].each do |to|
    next if vis[to]
    return true if can_go?(to, y, path, vis)
  end
  return false
end
n = gets.to_i
can_go = Array.new(105){Array.new}
interval = [[0, 0]]
n.times do
  p, a, b = gets.split(' ').map(&:to_i)
  if p == 1
    for i in 1...interval.size
      c, d = interval[i]
      can_go[interval.size] << i if((c < a && a < d) || (c < b && b < d))
      can_go[i] << interval.size if((a < c && c < b) || (a < d && d < b))
    end
    interval << [a, b]
  else
    vis = Array.new(105, false)
    puts can_go?(a, b, can_go, vis) ? "YES" : "NO"
  end
end

def dfs(i)
	@visited[i] =  true
	@arr.each_with_index do |a,k|
		if @visited[k]
			next
			#@arr[i][0]-a,@arr[i][1]- b, a[0] - c,a[1] - d
		elsif a[0] < @arr[i][0] && @arr[i][0] < a[1]
			dfs(k)
		elsif a[0] < @arr[i][1] && @arr[i][1] < a[1]
			dfs(k)
		end
	end
end

n = gets.to_i
@arr = []
n.times do
	m,a,b = gets.split(" ").map(&:to_i)
	if m == 1
		@arr << [a,b]
	else
		@visited = Hash.new(false)
		dfs(a-1)
		if @visited[b-1]
			puts "YES"
		else
			puts "NO"
		end
	end
end

def dfs (a, f, i)
  x, y = a[i]
  f[i] = true
  a.each_index do |j|
    nx, ny = a[j]
    next if f[j]
    dfs(a, f, j) if ((nx < x and x < ny) or (nx < y and y < ny))
  end
end

a = []
n = gets.strip.to_i
n.times do
  t, x, y = gets.strip.split(" ").collect{|v| v.to_i}
  if t == 1 then
    a << [x, y]
    next
  end

  f = Hash.new{|h,k| h[k] = false}
  dfs(a, f, x-1)
  f[y-1] ? (puts "YES") : (puts "NO")
end

# Define a func to update reachability matrix
def update_reach(reachabilty, intervals)
    reachabilty.push([])
    j = intervals.length - 1; c = intervals[j][1]; d = intervals[j][2];
    for i in 0..(j - 1) do
        a = intervals[i][1]; b = intervals[i][2];
        if (((c < a) && (a < d)) || ((c < b) && (b < d)))
            reachabilty[i].push(j)
        end
        if (((a < c) && (c < b)) || ((a < d) && (d < b)))
            reachabilty[j].push(i)
        end
    end
end

# Define a func to run dfs
def dfs(root, traversal, reachabilty)
    traversal[traversal.length] = root
    for child in reachabilty[root] do
        unless traversal.include?(child)
            dfs(child, traversal, reachabilty)
        end
    end
end

# Initialize variables
n = 0; queries = []; traversal = []; reachabilty = []; intervals = [];

# Read input
n = gets.strip.to_i
n.times {queries.push(gets.strip.split.map{|s| s.to_i})}

# Loop over queries
for i in 0..(n - 1) do
    if queries[i][0] == 1
        intervals.push(queries[i])
        update_reach(reachabilty, intervals)
    else
        traversal = []; root, target = queries[i][1,2].map{|k| k - 1};
        dfs(root,traversal,reachabilty)
        puts traversal.include?(target) ? "YES" : "NO"
    end
end

#! ruby -Ku
# -*- coding: UTF-8 -*-

def check_movability(start, goal)
  if start == nil || goal == nil
    return false
  end
  a = start[0]
  b = start[1]
  c = goal[0]
  d = goal[1]
  if (c < a && a < d) || (c < b && b < d)
    return true
  else
    return false
  end
end

def answer(intervals, query)
  intervals.each do |elem|
    if elem != nil
      elem[2] = false
    end
  end

  current = intervals[query.shift-1]
  goal = intervals[query.shift-1]
  if current == nil || goal == nil
    return false
  end
  stack = Array::new
  stack.push(current)

  while stack.size != 0
    current = stack.pop
    if check_movability(current, goal)
      return true
    else
      current[2] = true
      intervals.each do |elem|
        if check_movability(current, elem) && !elem[2]
          stack.push(elem)
        end
      end
    end
  end

  return false
end

# file = open("input.txt")
# total_line = file.gets.to_i
total_line = gets.to_i

intervals = Array::new
queries = Array::new

total_line.times do |i|
  # input = file.gets.split.map(&:to_i)
  input = gets.split.map(&:to_i)
  if input.shift == 1
    input << false
    intervals << input
  else
    check = answer(intervals, input)
    if check == true
      puts "YES"
    else
      puts "NO"
    end
  end
end

def compute_reachability arr, index
  (1..index).each do |k|
    (1..index).each do |i|
      (1..index).each do |j|
        if (arr[i][j] == nil) && arr[i][k] !=nil && arr[k][j] != nil
          arr[i][j] = 1
        end
      end
    end
  end
end

n = gets.to_i
arr = Array.new(n + 1) {Array.new(n + 1)}
intervals = []
(1..n).each { |i| arr[i][i] = nil}
(1..n).each do |index|
  command, x, y = gets.split(' ').map(&:to_i)
  if command == 1
    current = intervals.length + 1
    intervals.each_with_index do |interval, i|
      a,b = interval[0], interval[1]
      if ( a < x && x < b) ||  ( a < y && y < b)
        arr[current][i +1] = 1
      end
      if (x < a && a < y) ||  ( x < b && b < y)
        arr[i +1][current] = 1
      end
    end
    compute_reachability(arr, current)
    intervals << [x,y]
  else
    puts  arr[x][y]!=nil ? "YES" : "NO"
  end

end

def dfs(i)
	@visited[i] =  true
	@arr.each_with_index do |a,k|
		if @visited[k]
			next
			#@arr[i][0]-a,@arr[i][1]- b, a[0] - c,a[1] - d
		elsif a[0] < @arr[i][0] && @arr[i][0] < a[1]
			dfs(k)
		elsif a[0] < @arr[i][1] && @arr[i][1] < a[1]
			dfs(k)
		end
	end
end

n = gets.to_i
@arr = []
n.times do
	m,a,b = gets.split(" ").map(&:to_i)
	if m == 1
		@arr << [a,b]
	else
		@visited = Hash.new(false)
		dfs(a)
		if @visited[b]
			puts "YES"
		else
			puts "NO"
		end
	end
end

def dfs (a, f, i)
  x, y = a[i]
  f[i] = true
  a.each_index do |j|
    nx, ny = a[j]
    next if f[j]
    dfs(a, f, j) if ((nx < x and x < ny) or (nx < y and y < ny))
  end
end

a = []
f = Hash.new{|h,k| h[k] = false}
n = gets.strip.to_i
n.times do
  t, x, y = gets.strip.split(" ").collect{|v| v.to_i}
  if t == 1 then
    a << [x, y]
    next
  end

  dfs(a, f, x-1)
  f[y-1] ? (puts "YES") : (puts "NO")
end

#! ruby -Ku
# -*- coding: UTF-8 -*-

def check_movability(start, goal)
  if start == nil || goal == nil
    return false
  end
  a = start[0]
  b = start[1]
  c = goal[0]
  d = goal[1]
  if (c < a && a < d) || (c < b && b < d)
    return true
  else
    return false
  end
end

def answer(intervals, query)
  intervals.each do |elem|
    if elem != nil
      elem[2] = false
    end
  end

  current = intervals[query.shift-1]
  goal = intervals[query.shift-1]
  if current == nil || goal == nil
    return false
  end
  stack = Array::new
  stack.push(current)

  while stack.size != 0
    current = stack.pop
    if check_movability(current, goal)
      return true
    else
      current[2] = true
      intervals.each do |elem|
        if check_movability(current, elem) && !elem[2]
          stack.push(elem)
        end
      end
    end
  end

  return false
end

# file = open("input.txt")
# total_line = file.gets.to_i
total_line = gets.to_i

intervals = Array::new
queries = Array::new

total_line.times do |i|
  # input = file.gets.split.map(&:to_i)
  input = gets.split.map(&:to_i)
  if input.shift == 1
    input << false
    intervals[i] = input
  else
    check = answer(intervals, input)
    if check == true
      puts "YES"
    else
      puts "NO"
    end
  end
end

def compute_reachability arr, index
  (1..index).each do |i|
    (1..index).each do |j|
      if (arr[i][j] == nil) && arr[i][index] == 1 && arr[index][j] == 1
        arr[i][j] = 1
      end
    end
  end
end

n = gets.to_i
arr = Array.new(n + 1) {Array.new(n + 1)}
intervals = []
(1..n).each { |i| arr[i][i] = 0}
(1..n).each do |index|
  command, x, y = gets.split(' ').map(&:to_i)
  if command == 1
    intervals.each_with_index do |interval, i|
      if (x < interval[1] && x > interval[0]) ||  (y < interval[1] && y > interval[0])
        arr[index][i +1] = 1
      end
      if (interval[0] < y && interval[0] > x) ||  ( interval[1] < y && interval[1] > x)
        arr[i +1][index] = 1
      end
    end
    compute_reachability(arr, index)
    intervals << [x,y]
  else
    puts  arr[x][y]== 1 ? "YES" : "NO"
  end

end


You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases.

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 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. 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: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp.split("").map(&:to_i)
  one_fin = 0
  zero_fin = 0
  index = 0
  arr = Array.new(n)
  max = 0
  n.times do |i|
    if s[i] == 1
      if zero_fin > 0
        one_fin += 1
        zero_fin -= 1
        index += 1
        arr[i] =  index
      else
        one_fin += 1
        arr[i] = one_fin
        index += 1
        max = one_fin if max < one_fin
      end
    elsif s[i] == 0
      if one_fin > 0
        zero_fin += 1
        one_fin -= 1
        arr[i] = index
        index -= 1
      else
        zero_fin += 1
        arr[i] = zero_fin
        max = zero_fin if max < zero_fin
      end
    end
  end
  ans << [arr,max]
end
ans.each do |ar|
  puts ar[1]
  ar[0].each do |x|
    print "#{x} "
  end
  puts ""
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp.split("")
  one_fin = 0
  zero_fin = 0
  index = 0
  arr = Array.new(n)
  max = 0
  n.times do |i|
    if s[i] == "1"
      if zero_fin > 0
        one_fin += 1
        zero_fin -= 1
        index += 1
        arr[i] =  index
      else
        one_fin += 1
        arr[i] = one_fin
        index += 1
        max = one_fin if max < one_fin
      end
    elsif s[i] == "0"
      if one_fin > 0
        zero_fin += 1
        one_fin -= 1
        arr[i] = index
        index -= 1
      else
        zero_fin += 1
        arr[i] = zero_fin
        max = zero_fin if max < zero_fin
      end
    end
  end
  ans << [arr,max]
end
ans.each do |ar|
  puts ar[1]
  ar[0].each do |x|
    print "#{x} "
  end
  puts ""
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp
  one_fin = 0
  zero_fin = 0
  index = 0
  arr = []
  n.times do |i|
    if s[i] == "0" && one_fin > 0
      zero_fin += 1
      one_fin -= 1
      arr << index
      index -= 1
    elsif s[i] == "0" && one_fin > 0
      zero_fin += 1
      arr << zero_fin
    elsif s[i] == "0" && zero_fin > 0
      one_fin += 1
      zero_fin -= 1
      index += 1
      arr << index
    else
      one_fin += 1
      arr << one_fin
      index += 1
    end
  end
  ans << arr
end
ans.each do |ar|
  puts ar.max
  ar.each do |x|
    print "#{x} "
  end
  puts ""
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp
  one_i = 1
  zero_i = 1
  arr = []
  n.times do |i|
    if s[i] == "0"
      if zero_i < one_i
        one_i -= 1
        arr << one_i
      else
        arr << zero_i
        zero_i += 1
      end
    elsif s[i] == "1"
      if zero_i > one_i
        zero_i -= 1
        arr << zero_i
      else
        arr << one_i
        one_i += 1
      end
    end
  end
  ans << arr
end
ans.each do |ar|
  puts ar.max
  ar.each do |x|
    print "#{x} "
  end
  puts ""
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp
  one_i = 1
  zero_i = 1
  arr = []
  n.times do |i|
    if s[i] == "0"
      if zero_i < one_i
        one_i -= 1
        arr << one_i
      else
        arr << zero_i
        zero_i += 1
      end
    elsif s[i] == "1"
      if zero_i > one_i
        zero_i -= 1
        arr << zero_i
      else
        arr << one_i
        one_i += 1
      end
    end
  end
  ans << arr
end
ans.each do |ar|
  ar.each do |x|
    print "#{x} "
  end
  puts ""
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  s = gets.chomp
  one_fin = 0
  zero_fin = 0
  arr = []
  n.times do |i|
    if s[i] == "0"
      if one_fin > 0
        zero_fin += 1
        arr << zero_fin
        one_fin -= 1
      else
        zero_fin += 1
        arr << zero_fin
      end
    elsif s[i] == "1"
      if zero_fin > 0
        one_fin += 1
        arr << one_fin
        zero_fin -= 1
      else
        one_fin += 1
        arr << one_fin
      end
    end
  end
  ans << arr
end
ans.each do |ar|
  puts ar.max
  ar.each do |x|
    print "#{x} "
  end
  puts ""
end


«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).Your task is to write a part of the program, responsible for «standardization» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 < li + 1 for all i from 1 to k - 1, and li ≤ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as «li - li».For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.

The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.

Output the sequence in the required format.

s = gets.split(",")
s = s.collect {|i| i = i.to_i}
s = s.sort
s = s.uniq
i = s.size-1
while i>0 do
    k = s[i].to_i
    if k == s[i-1] + 1 then
        if t = s[i].to_s.index("-") then s[i] = s[i][t+1...s[i].size].to_i
        end
        s[i-1] = s[i-1].to_s + "-" + s[i].to_s
        s.delete_at(i)
    end
    i -= 1
end
str = s.join(",")
print "#{str}\n"

sa = gets.chomp.split(/,/)
sa.map!{|x| x.to_i}
sa.uniq!
sa.sort!

ret = ""
st = 0
prev = 0
for i in 0..sa.length-1
	if st == 0
		ret += sa[i].to_s
		st = sa[i]
		prev = st
	else
		if sa[i] == prev+1
			prev = sa[i]
		else
			if st == prev
				ret +=  "," + sa[i].to_s
			else
				ret +=  "-" + prev.to_s + "," + sa[i].to_s
			end
			st = sa[i]
			prev = st
		end
	end
end

if st != prev
	ret +=  "-" + prev.to_s
end

puts ret

a = gets.split(',').map(&:to_i).sort
b = []
s = t = a[0]
a.each do |i|
	if i <= t + 1 then
		t = i
	else
		b << [s, t]
		s = t = i
	end
end
b << [s, t]
puts b.map{|a, b| a == b ? a : "#{a}-#{b}"} * ','

__END__

pages = gets.strip.split(",").map{|s| s.to_i}
inc = [false] * 2000
pages.each {|n| inc[n] = true}

i = 1
was = false
while i <= 1000
  unless inc[i]
    i += 1
    next
  end
  print "," if was
  j = i+1
  j += 1 while inc[j]
  print i
  print "-",j-1 if j > i+1
  was = true
  i = j
end

pages = gets.strip.split(",").map{|s| s.to_i}
inc = [false] * 2000
pages.each {|n| inc[n] = true}

i = 1
res = []
while i <= 1000
  unless inc[i]
    i += 1
    next
  end
  j = i+1
  j += 1 while inc[j]
  if j == i+1
    res << i
  else
    res << [i, "-", j-1].join("")
  end
  i = j
end

puts res.join(",")

#!usr/bin/env ruby
x=gets()
array=x.split(',')
#puts(array)
array2=Array.new()
array.each do
    |a|
    a=a.to_i
    #puts(a)
    array2 << a
end
array2.sort!
array2 = array2 & array2
#puts(array2)
prev = -1
res = ""
last=0
for x in array2 do
        if x-prev != 1 then
            if prev !=-1 && last != prev then
                res << "-" << prev.to_s
                last = prev
            end
            if res == "" then
                res << x.to_s
                last = x
            else
                res << ","
                res << x.to_s
                last = x
            end
        end
        prev = x
    end
    if last != prev then
        res << "-" << prev.to_s
    end
puts (res)

#!usr/bin/env ruby
x=gets()
array=x.split(',')
#puts(array)
array2=Array.new()
array.each do
    |a|
    a=a.to_i
    #puts(a)
    array2 << a
end
array2.sort!
array2 = array2 & array2
#puts(array2)
prev = -1
res = ""
last=0
for x in array2 do
        if x-prev != 1 then
            if prev !=-1 then
                res << "-" << prev.to_s
                last = prev
            end
            if res == "" then
                res << x.to_s
                last = x
            else
                res << ","
                res << x.to_s
                last = x
            end
        end
        prev = x
    end
    if last != prev then
        res << "-" << prev.to_s
    end
puts (res)


In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.

The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.

If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).

20 ml. from cup #4 to cup #1.
Exemplary pages.
Unrecoverable configuration.

n = gets.to_i
a = n.times.map{gets.to_i}
s = a.inject &:+
k = a.find_all{|_| _ != s / n}.map{|_| a.index _}
if s % n != 0 || (!k.empty? && k.size != 2)
	puts 'Unrecoverable configuration.'
elsif k.empty?
	puts 'Exemplary pages.'
else
	i, j = *k
	i, j = j, i if a[i] < a[j]
	puts "#{(a[i] - a[j]) / 2} ml. from cup ##{j + 1} to cup ##{i + 1}."
end

n=gets.to_i
a=[]
n.times{
    a.push(gets.to_i)
}
ok=1
(n-1).times{|i|
    if a[i]!=a[i+1] then
        ok=0
        break
    end
}
if ok==1 then
    puts "Exemplary pages."
    exit
end
cnt={}
cnt.default=0
a.each{|i|
    cnt[i]+=1
}
if cnt.length<5 then
    n.times{|i|
        if cnt[a[i]]==1 then
            n.times{|j|
                if cnt[a[j]]==1 then
                    if a[i]>a[j] then
                        v=a[i]-a[j]
                        v/=2
                        a[i]-=v
                        a[j]+=v
                        ok=1
                        (n-1).times{|i|
                            if a[i]!=a[i+1] then
                            ok=0
                            break
                            end
                        }
                        if ok==1 then
                            printf "%d ml. from cup #%d to cup #%d.\n",v,j+1,i+1
                            exit
                        end
                        a[i]+=v
                        a[j]-=v;
                    end
                end
            }
        end
    }
end
puts "Unrecoverable configuration."

def check(a, b, n)
	diff = b[0]-a[0]
	if diff.odd? || (a[0]+b[0])/2 != n
		puts "Unrecoverable configuration."
		exit
	end
	puts "#{(diff)/2} ml. from cup ##{a[1]} to cup ##{b[1]}."
	exit
end

n = gets.to_i
arr = Array.new(n) { |idx| [gets.to_i, idx+1] }.sort.freeze

if arr[0][0] == arr[-1][0]
	puts "Exemplary pages."
	exit
end

if arr.size == 2
	diff = arr[1][0]-arr[0][0]
	if diff.odd?
		puts "Unrecoverable configuration."
		exit
	end
	check(arr[0], arr[1], (arr[0][0]+arr[1][0])/2)
end

if arr[1][0] != arr[-2][0]
	puts "Unrecoverable configuration."
	exit
end

check(arr[0], arr[-1], arr[1][0])

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
if count.keys.count == 1
  puts 'Exemplary pages.'
  exit
end

def fail
  puts 'Unrecoverable configuration.'
  exit
end

cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1

cups[0][0] += pour
cups[-1][0] -= pour
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
fail if count.keys.count != 1

puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

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

ls = $stdin.readlines.map(&:chomp)
n = ls[0].to_i
vs = ls.drop(1).map(&:to_i)

s = vs.inject(0, &:+)
if s % n != 0
  puts 'Unrecoverable configuration.'
  exit 0
end
ave = s / n

a = []
vs.each_with_index do |v, i|
  if v != ave
    a << [v, i]
  end
end
if a.empty?
  puts 'Exemplary pages.'
elsif a.size == 2 and a[0][0] + a[1][0] == ave * 2
  x, y = a.sort
  puts "#{ave - x[0]} ml. from cup ##{x[1]+1} to cup ##{y[1]+1}."
else
  puts 'Unrecoverable configuration.'
end

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
# arr.sort!
sorted = arr.sort
normal = sorted[1]
chunk = sorted.chunk{|x| x}
# puts "#{chunk.count}"
ans = false
if chunk.count == 1
	puts "Exemplary pages."
	ans = true
elsif chunk.count == 2 || chunk.count == 3
	min,min_ind,max,max_ind = arr.each_with_index.minmax.flatten
	# puts "min #{min} ind #{min_ind} #{max} #{max_ind}" if n == 198
	# puts "#{arr.count(min) == 1  && arr.count(max) == 1}"

	el = (min + max) / 2
	ml = max - el

	if (arr.count(min) == 1)  && (arr.count(max) == 1) && (el-min == ml)
		if !(chunk.count == 3 && el != normal)
			ans = true
			puts "#{ml} ml. from cup ##{min_ind+1} to cup ##{max_ind+1}."
		end
	end
end

puts "Unrecoverable configuration." unless ans

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num != 2 + (n > 2 ? 1 : 0)
cups.sort!
fail if n > 3 and cups[1][0] != cups[-2][0]
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num != 2 + (n > 2 ? 1 : 0)
fail if n > 3 and cups[1] != cups[-2]
cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num > 3 or n > 2 and key_num == 2
cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num > 3
cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num > 3
cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[-1][1]+1, cups[0][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

n = STDIN.readline.to_i
cups = []
n.times {|ix| cups.push([STDIN.readline.to_i, ix]) }
count = Hash.new(0)
cups.each {|volume, ix| count[volume] += 1 }
key_num = count.keys.count
if key_num == 1
  puts 'Exemplary pages.'
  exit
end
def fail
  puts 'Unrecoverable configuration.'
  exit
end
fail if key_num > 3 or (n > 2 and key_num == 2)
cups.sort!
delta = cups[-1][0] - cups[0][0]
fail if delta % 2 == 1
pour, source, target = delta/2, cups[0][1]+1, cups[-1][1]+1
puts '%d ml. from cup #%d to cup #%d.' % [pour, source, target]

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

ls = $stdin.readlines.map(&:chomp)
n = ls[0].to_i
vs = ls.drop(1).map(&:to_i)

s = vs.inject(0, &:+)
if s % n != 0
  puts 'Unrecoverable configuration.'
  exit 0
end

a = []
vs.each_with_index do |v, i|
  if v != s / n
    a << [v, i]
  end
end
if a.empty?
  puts 'Exemplary pages.'
elsif a.size == 2 and a[0][0] + a[1][0] == s / n * 2
  x, y = a.sort
  puts "#{s/n - x[0]} ml. from cup ##{x[1]+1} to cup ##{y[1]+1}."
else
  puts 'Unrecoverable configuration'
end

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

ls = $stdin.readlines.map(&:chomp)
n = ls[0].to_i
vs = ls.drop(1).map(&:to_i)

s = vs.inject(0, &:+)
if s % n != 0
  puts 'Unrecoverable configuration.'
  exit 0
end

a = []
vs.each_with_index do |v, i|
  if v != s / n
    a << [v, i]
  end
end
if a.empty?
  puts 'Exemplay pages.'
elsif a.size == 2 and a[0][0] + a[1][0] == s / n * 2
  x, y = a.sort
  puts "#{s/n - x[0]} ml. from cup ##{x[1]+1} to cup ##{y[1]+1}."
else
  puts 'Unrecoverable configuration'
end

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
# arr.sort!
chunk = arr.sort.chunk{|x| x}
# puts "#{chunk.count}"
if chunk.count == 1
	puts "Exemplary pages."
elsif chunk.count == 2 || chunk.count == 3
	min,min_ind,max,max_ind = arr.each_with_index.minmax.flatten
	# puts "min #{min} ind #{min_ind} #{max} #{max_ind}" if n == 198
	# puts "#{arr.count(min) == 1  && arr.count(max) == 1}"

	el = (min + max) / 2
	ml = max - el

	if (arr.count(min) == 1)  && (arr.count(max) == 1) && el == arr.sort[1] && (el-min == ml)

		puts "#{ml} ml. from cup ##{min_ind+1} to cup ##{max_ind+1}."
	else
		puts "Unrecoverable configuration."
	end
else
	puts "Unrecoverable configuration."
end

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
# arr.sort!
chunk = arr.sort.chunk{|x| x}
# puts "#{chunk.count}"
if chunk.count == 1
	puts "Exemplary pages."
elsif chunk.count == 3
	min,min_ind,max,max_ind = arr.each_with_index.minmax.flatten
	# puts "min #{min} ind #{min_ind} #{max} #{max_ind}"
	# puts "#{arr.count(min) == 1  && arr.count(max) == 1}"
	if (arr.count(min) == 1)  && (arr.count(max) == 1)

		el = (min + max) / 2
		ml = max - el

		puts "#{ml} ml. from cup ##{min_ind+1} to cup ##{max_ind+1}."
	else
		puts "Unrecoverable configuration."
	end
else
	puts "Unrecoverable configuration."
end

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
# arr.sort!
chunk = arr.sort.chunk{|x| x}
# puts "#{chunk.count}"
if chunk.count == 1
	puts "Exemplary pages."
elsif chunk.count == 2 || chunk.count == 3
	min,min_ind,max,max_ind = arr.each_with_index.minmax.flatten
	# puts "min #{min} ind #{min_ind} #{max} #{max_ind}"
	# puts "#{arr.count(min) == 1  && arr.count(max) == 1}"

	el = (min + max) / 2
	ml = max - el
	if (arr.count(min) == 1)  && (arr.count(max) == 1) && (el-min == ml)

		puts "#{ml} ml. from cup ##{min_ind+1} to cup ##{max_ind+1}."
	else
		puts "Unrecoverable configuration."
	end
else
	puts "Unrecoverable configuration."
end

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
# arr.sort!
chunk = arr.sort.chunk{|x| x}
# puts "#{chunk.count}"
if chunk.count == 1
	puts "Exemplary pages."
elsif chunk.count == 2 || chunk.count == 3
	min,min_ind,max,max_ind = arr.each_with_index.minmax.flatten
	puts "min #{min} ind #{min_ind} #{max} #{max_ind}" if n == 198
	# puts "#{arr.count(min) == 1  && arr.count(max) == 1}"

	el = (min + max) / 2
	ml = max - el

	if (arr.count(min) == 1)  && (arr.count(max) == 1) && (el-min == ml)

		puts "#{ml} ml. from cup ##{min_ind+1} to cup ##{max_ind+1}."
	else
		puts "Unrecoverable configuration."
	end
else
	puts "Unrecoverable configuration."
end


Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".

The first line contains a non-empty string s, consisting of lowercase Latin letters — that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≤ k ≤ 13) — the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.

Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.

NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.

s = gets.chomp
k = gets.to_i
$h = {}
for i in 0..k-1
	w = gets.chomp
	$h[w[0]] = i
	$h[w[1]] = i
end

i = 0
count = 0
while(i < s.length)
	c = s[i]
	g = $h[c]
	i += 1
	f = 1
	t = 1
	while(i < s.length && $h.key?(s[i]) && g == $h[s[i]])
		if(s[i] == c)
			f += 1
		end
		t += 1
		i += 1

	end

	#puts c + ": "  + [f, t - f].min.to_s
	count += [f, t - f].min
end
puts count

s = gets.chomp
k = gets.to_i
$h = {}
for i in 0..k-1
	w = gets.chomp
	if $h.key? (w[0])
		$h[w[0]] = $h[w[0]] << w[1]
	else
		$h[w[0]] = [w[1]]
	end

	if $h.key? (w[1])
		$h[w[1]] = $h[w[1]] << w[0]
	else
		$h[w[1]] = [w[0]]
	end
end

$dp = {}

def minEdit s,i
	if i >= s.length - 1
		return 0
	elsif ($h.key?(s[i]) && $h[s[i]].include?(s[i + 1]))
		a = s.dup
		a.slice! (i)
		b = s.dup
		b.slice! (i + 1)
		kl = a#a.slice([i - 1, 0].max..s.length - 1)
		kr = b#b.slice(i..s.length - 1)
		#puts "kl: " + kl
		#puts "kr: " + kr
		left = 0
		right = 0
		if $dp.key? kl
			left = $dp[kl]
		else
			left = minEdit(a, [i - 1, 0].max)
			$dp[kl] = left
		end
		if $dp.key? kr
			right = $dp[kr]
		else
			right = minEdit(b, i)
			$dp[kr] = right
		end
		puts "kl: " + kl + ", " + left.to_s
		puts "kr: " + kr + ", " + right.to_s
	  	ret = [left, right].min + 1
	else
		return minEdit s, (i + 1)
	end
end

puts minEdit(s, 0)

s = gets.chomp
k = gets.to_i
$h = {}
for i in 0..k-1
	w = gets.chomp
	$h[w[0]] = i
	$h[w[1]] = i
end

i = 0
count = 0
while(i < s.length)
	c = s[i]
	g = $h[c]
	i += 1
	f = 1
	t = 1
	while(i < s.length && g == $h[s[i]])
		if(s[i] == c)
			f += 1
		else
			t += 1
		end
		i += 1
		count += [f, t - f].min
	end
end
puts count


This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).In this problem you should guess an array a which is unknown for you. The only information you have initially is the length n of the array a.The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices i and j (the indices should be distinct). Then your program should read the response: the single integer equals to ai + aj.It is easy to prove that it is always possible to guess the array using at most n requests.Write a program that will guess the array a by making at most n requests.

NoteThe format of a test to make a hack is:  The first line contains an integer number n (3 ≤ n ≤ 5000) — the length of the array. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array to guess.

size = gets.to_i
done = true
i=1
tableau_de_somme = []
tableau_final = []
tableau_final[0] = "!"

while done do
	puts "?"+ " " + i.to_s + " " + (i+=1).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
	done = false if i == size
end

resultat = []
resultat[0] = 0
a = 0

while a < (size-2) do
	resultat[0] += tableau_de_somme[a]
	resultat[0] -= tableau_de_somme[a += 1]
	a += 1
end

if size.modulo(2) == 0
	puts "?"+ " " + 1.to_s + " " + (size-1).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
else
	puts "?"+ " " + 1.to_s + " " + (size).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
end

resultat[0] += tableau_de_somme[size-1]
resultat[0] /= 2
tableau_final << resultat[0]

tableau_de_somme.each do |val|
	tableau_final << val - tableau_final.last
end

tableau_final.pop

tableau_final.each do |val|
	print val.to_s + " "
	$stdout.flush
end

#!/usr/bin/ruby

size = gets.to_i
resolu = true
i=1
tableau_de_somme = []
tableau_final = []
tableau_final[0] = "!"

while resolu do
	puts "?"+ " " + i.to_s + " " + (i+=1).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
	resolu = false if i == size
end
resultat = []
resultat[0] =0
iterator=0
while iterator < (size-2) do
	resultat[0] += tableau_de_somme[iterator]
	resultat[0] -= tableau_de_somme[iterator+=1]
	iterator+=1
end
if size.modulo(2) == 0
	puts "?"+ " " + 1.to_s + " " + (size-1).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
else
	puts "?"+ " " + 1.to_s + " " + (size).to_s
	$stdout.flush
	tableau_de_somme << gets.to_i
end
resultat[0] += tableau_de_somme[size-1]
resultat[0] /= 2
tableau_final << resultat[0]

tableau_de_somme.each do |val|
	tableau_final << val - tableau_final.last
end
tableau_final.pop
tableau_final.each do |val|
	print val.to_s + " "
	$stdout.flush
end

size = gets.to_i
resolu = true
indice=0
i=1
puts indice
tableau_de_somme = []
tableau_final = []
tableau_final[0] = "!"

while resolu do
    $stdout.print "?"+ " " + i.to_s + " " + (i+=1).to_s
    $stdout.flush
    tableau_de_somme << gets.to_i
    resolu = false if i == size
end
resultat = []
resultat[0] =0
iterator=0
while iterator < (size-2) do
    resultat[0] += tableau_de_somme[iterator]
    resultat[0] -= tableau_de_somme[iterator+=1]
    iterator+=1
end
if size.modulo(2) == 0
    $stdout.print "?"+ " " + 1.to_s + " " + (size-1).to_s
    $stdout.flush
    tableau_de_somme << gets.to_i
else
    $stdout.print "?"+ " " + 1.to_s + " " + (size).to_s
    $stdout.flush
    tableau_de_somme << gets.to_i
end
resultat[0] += tableau_de_somme[size-1]
resultat[0] /= 2
tableau_final << resultat[0]

tableau_de_somme.each do |val|
    tableau_final << val - tableau_final.last
end
tableau_final.pop
tableau_final.each do |val|
    print val.to_s + " "
end


Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.

The first line contains three integers n,x,y (1 ≤ n ≤ 105, 1 ≤ x, y ≤ 106) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1 ≤ ai ≤ 109) — the number of hits needed do destroy the i-th monster.

Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.

NoteIn the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.

n, x, y = gets.split.map(&:to_i)
xy = x + y

g = []
n.times do
  g << gets.to_i
end

g.each do |health|
  health %= xy
  hitsx = health * x / xy
  hitsy = health * y / xy
  health -= hitsx + hitsy
  tx = hitsx * y
  ty = hitsy * x
  while 0 < health
    tx1, ty1 = tx + y, ty + x
    if tx1 < ty1
      tx = tx1
      health -= 1
    elsif ty1 < tx1
      ty = ty1
      health -= 1
    else
      tx, ty = tx1, ty1
      health -= 1
    end
  end
  if tx < ty
    puts 'Vova'
  elsif ty < tx
    puts 'Vanya'
  else
    puts 'Both'
  end
end

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

F = "Vonya"
S = "Vova"
B = "Both"
n, x, y = gets.split.map(&:to_i)
one = x + y
ans = []
l = []
n.times do
  a_i = gets.to_i
  if x == y
    puts B
    next
  end
  remain = a_i % one
  remain.times do |i|
    a = (i + 1) / x.to_f
    b = (i + 1) / y.to_f
    next if l.index([a, F]) or l.index([b, S])
    l << [a, F]
    l << [b, S]
  end
  l.sort!
  index = remain - 1
  if ans[index]
    puts ans[index]
    next
  end
  c = l[index]
  before = l[index - 1] if 0 < index
  after  = l[index + 1] if index < l.length
  if (before and c[0] == before[0]) or (after and c[0] == after[0])
    ans[index] = B
  else
    ans[index] = c[1]
  end
  puts ans[index]
end

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

F = 'Vanya'
S = 'Vova'
B = 'Both'

def ans_list(x, y)
  l = []
  (x+y).times do |i|
    a = (i + 1) / x.to_f
    b = (i + 1) / y.to_f
    l << [a, F] if l.length < (x + y)
    l << [b, S] if l.length < (x + y)
    break if (x + y) <= l.length
  end
  l.sort
end

n,x,y = gets.chomp.split.map(&:to_i)
l = ans_list(x, y)

one = x + y
ans = []
n.times do
  a_i = gets.chomp.to_i
  if x == y
    puts B
  else
    remain = a_i % one
    if ans[remain - 1]
      puts ans[remain - 1]
      next
    else
      index = remain - 1
      c      = l[index]
      before = l[index - 1] if 0 < index
      after  = l[index + 1] if index < l.length
      if (before and c[0] == before[0]) or (after and c[0] == after[0])
        ans[index] = B
      else
        ans[index] = c[1]
      end
      puts ans[index]
    end
  end
end

# ヒット数が等しい物があるかもしれないので結果をキャッシュする


Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 ≤ ai - bi ≤ k for all 1 ≤ i ≤ n.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).

The first line contains two integers n and k (1 ≤ n ≤ 3·105; 1 ≤ k ≤ 106). The second line contains n integers ai (1 ≤ ai ≤ 106) — array a.

In the single line print a single number — the maximum possible beauty of the resulting array.

NoteIn the first sample we can obtain the array:3 6 9 12 12 15In the second sample we can obtain the next array:7 21 49 14 77

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
MIN, MAX = a.minmax
if MIN <= k+1
  puts MIN
  exit
end

b = Array.new(MAX+1, 0)
a.each { |e| b[e] += 1 }
b.each_index do |i|
  b[i] += b[i-1] if i != 0
end

ans = MIN
loop do
  l = ans + k
  r = 2*ans - 1
  flag = true

  while r < MAX
    if b[l] < b[r]
      break flag = false
    end
    l += ans
    r += ans
  end

  break if flag && l >= MAX
  ans -= 1
end

puts ans

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
MIN, MAX = a.minmax
if MIN <= k+1
  puts MIN
  exit
end

b = Array.new(MAX+1, 0)
a.each { |e| b[e] += 1 }
b.each_index do |i|
  b[i] += b[i-1] if i != 0
end

ans = MIN
loop do
  l = ans + k
  r = 2*ans - 1
  flag = true

  loop do
    if r > MAX
      if l >= MAX
        break flag = true
      else
        if b[l] < b[MAX]
          break flag = false
        else
          break flag = true
        end
      end
    elsif b[l] < b[r]
      break flag = false
    end
    l += ans
    r += ans
  end

  break if flag
  ans -= 1
end
puts ans

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

loop do
  flag = true
  a.each do |e|
    while e % ans > k
      ans -= 1
      flag = false
    end
  end
  break if flag
end
puts ans

gets.scan(/(\d+) (\d+)/)
n=$1.to_i
k=$2.to_i
a=gets.scan(/\d+/).map {|s| s.to_i}.uniq.sort
l=Array.new(a.max+1, -1)
i=0
0.upto(a.max) {|j|
  if i<n && a[i]==j
    l[j+1]=a[i]
    i+=1
  else
    l[j+1]=l[j]
  end
}

a.first.downto(2){|divisor|
  existAns=true
  j=a.last
  while j>=a.first
    if j%divisor>k || j==a.first && j<divisor
      existAns=false
      break
    end
    j=l[j-j%divisor]
  end
  if existAns
    p divisor
    exit
  end
}
p 1

gets.scan(/(\d+) (\d+)/)
n=$1.to_i
k=$2.to_i
a=gets.scan(/\d+/).map {|s| s.to_i}.uniq.sort
l=Array.new(a.max+1, -1)
(0..a.size-2).each{|i|
  l.fill(a[i], a[i]+1..a[i+1])
}

a.first.downto(2){|divisor|
  existAns=true
  j=a.last
  while j>=a.first
    if j%divisor>k
      existAns=false
      break
    end
    j=l[j-j%divisor]
  end
  if existAns
    p divisor
    exit
  end
}
p 1

n, k = gets.split(' ').map {|x| x.to_i}
a = gets.split(' ').map {|x| x.to_i}.sort
minv, maxv = a.minmax

cnt = (Array.new maxv + 5).fill(0)
a.each {|x| cnt[x] += 1}
cnt.each_index {|i| cnt[i] += cnt[i - 1] if (i > 0)}
cnt[-1] = 0 # guard

(puts minv; exit) if (minv <= k + 1)

ans = minv
loop do
	l, r = k, ans - 1
	flag = 1
	while (l <= maxv) do
		r = maxv if (r > maxv)
		(flag = 0; break) if (cnt[r] > cnt[l])
		l += ans
		r += ans
	end
	break if (flag == 1)
	ans -= 1
end
puts ans

gets.scan(/(\d+) (\d+)/)
n=$1.to_i
k=$2.to_i
a=gets.scan(/\d+/).map {|s| s.to_i}.uniq.sort

p (1..a.first).to_a.delete_if {|divisor| a.reject!{|x|x%divisor>k || x==a.first && x<divisor}!=nil}.last

gets.scan(/(\d+) (\d+)/)
n=$1.to_i
k=$2.to_i
a=gets.scan(/\d+/).map {|s| s.to_i}.sort
l=Array.new(a.max+1, -1)
i=0
0.upto(a.max) {|j|
  if i<n && a[i]==j
    l[j+1]=a[i]
    i+=1
  else
    l[j+1]=l[j]
  end
}

a.first.downto(2){|divisor|
  existAns=true
  j=a.last
  while j>=a.first
    if j%divisor>k || j==a.first && j<divisor
      existAns=false
      break
    end
    j=l[j-j%divisor]
  end
  if existAns
    p divisor
    exit
  end
}
p 1


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.The decreasing coefficient of permutation p1, p2, ..., pn is the number of such i (1 ≤ i < n), that pi > pi + 1.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.

The single line contains two space-separated integers: n, k (1 ≤ n ≤ 105, 0 ≤ k < n) — the permutation length and the decreasing coefficient.

In a single line print n space-separated integers: p1, p2, ..., pn — the permutation of length n with decreasing coefficient k.  If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.

n,k = gets.split.map &:to_i
to = n-k
for i in (1..to-1)
    print "#{i} "
end
for i in (to+1..n)
    print "#{n-i+to+1} "
end
print to

require 'scanf'
(n, k) = scanf("%d%d")
# (n, k) = gets.chomp.split(' ').map(&:to_i)
a = Array.new(n)
(1..n).each do |i|
  a[i-1] = (i<=k) ? (n-i+1) : (i-k)
end
puts a.join(' ')

n,k=gets.split.map(&:to_i)
a=[]
n.downto(1){|x|a<<x}
a[0,k+1]=a[0,k+1].reverse
puts a.reverse*' '

n,k = gets.split.map &:to_i
    for i in (1..n-k-1)
      print i.to_s+" "
    end
    i=n
    while i>=n-k
        print i.to_s+" "
        i-=1
    end
    puts ""

n, k = gets.split.map(&:to_i)
puts ((1...(n - k)).to_a + n.downto(n - k).to_a).join(' ')

a=gets.chomp.split(" ")
n=a[0].to_i
k=a[1].to_i
k.times do
printf "#{n} "
n-=1
end

1.upto(n) do |i|
printf "#{i} "
end

n, k = gets.split.map(&:to_i)
(1..k).each{|i| print n-i+1, ' '}
(1..(n-k)).each{|i| print i, ' '}

#!/usr/bin/env ruby

n, k = gets.split.collect{ |i| i.to_i }

k.downto(0) { |i| print "#{i+1} " }
(k+2).upto(n) { |i| print "#{i} " }

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

(1..n)
result = (k+1).downto(1).to_a + (k+2..n).to_a

puts result.join(' ')

n, k = gets.split(' ').map(&:to_i)
ans = (0...k).map{|x| n-x} + (1..n-k).map{|x| x}
puts ans.map(&:to_s).join(" ")

# -*- encoding: utf-8 -*-
n, k = gets.chomp.split( " " ).map{ |e| e.to_i }
array = (1 .. n).to_a

ans = array[0 .. k].reverse() + array[k + 1 .. n]
puts ans.join " "

st = gets.split
n=st[0].to_i
k=st[1].to_i

el=n
(k).times do
  print(el," ")
  el-=1
end

el=1
(n-k).times do
  print(el," ")
  el+=1
end

n, k = gets.split.map { |i| i.to_i }
a = (1..n).to_a
a = a[0..-(k + 2)] + a[-(k + 1)..-1].reverse

a.each do |i|
  print i, ' '
end
puts

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

a = Array.new

for i in 0...k
  a << n-i
end

for i in 1..n-k
  a << i
end

for i in a
  print i, " "
end

#!/usr/bin/ruby1.9

n, k = STDIN.readline.split.collect {|s| s.to_i }

prefix = (1..k+1).collect {|x| x }.reverse
suffix = (k+2..n).collect {|x| x }

puts (prefix+suffix).join(' ')

#!/usr/bin/env ruby

n, k = STDIN.readline.split.map{ |x| Integer(x)}

k.times do |i|
    print "#{n - i} "
end

(1..n-k).each do |i|
    print "#{i} "
end

puts

def run
  n, k = $stdin.gets.split.map(&:to_i)
  $stdout.puts ((k + 1).downto(1).to_a + (k + 2).upto(n).to_a).join(" ")
end

run if $0 == __FILE__

# cook your code here
n, k =gets.split(' ').map(&:to_i)

arr = Array(1..n)
arr.unshift(arr.pop(k).reverse)
puts arr.join(' ')

# cook your code here
n, k =gets.split(' ').map(&:to_i)

k_copy =k
arr = Array(1..n)
last_index = arr.size-1
ans_arr = []
n.times do
    while k>0 do
        ans_arr << arr[last_index]
        last_index-=1
        k-=1
    end
end

(n-k_copy).times do  |i|
    ans_arr << arr[i]
end

puts ans_arr.join(" ")

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

    list = (1..n).to_a

    flag = true

    ans = Array.new(n,nil)

    if k > 0
      index = -1
      k.times do
        ans[index] = list.shift
        index -= 1
      end

      index = 0
      (n-k).times do
        ans[index] = list.shift
        index += 1
      end
    else
      ans = list
    end

    puts ans.join(' ')
  end
end

a = A.new

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

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

((k+1)..n).each do |index|
  print index," "
end
k.downto(1) do |index|
  print index," "
end

# cook your code here
n, k =gets.split(' ').map(&:to_i)

arr = Array(1..n)
arr.unshift(arr.pop(k))
puts arr.join(' ')

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

    list = (1..n).to_a

    flag = true

    ans = Array.new(n,nil)

    if k > 0
      index = -1
      k.times do
        ans[index] = list.shift
        index -= 1
      end

      index = 0
      (n-k).times do
        ans[index] = list.shift
      end
    else
      ans = list
    end

    puts ans.join(' ')
  end
end

a = A.new

a=gets.chomp.split(" ")
c=a[0].to_i
b=a[1].to_i
trig=0
ans=[]
loop do
if ans.count(c%b)==0
ans << c%b
else
break
end

c=c+c%b
if c % b == 0
trig=1
break
end

end

if trig==1
puts "Yes"
else
puts "No"
end


This is an interactive problem.Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation $$$a_1, a_2, \dots, a_n$$$ of integers $$$1$$$ to $$$n$$$. You are asked to find any index $$$k$$$ ($$$1 \leq k \leq n$$$) which is a local minimum. For an array $$$a_1, a_2, \dots, a_n$$$, an index $$$i$$$ ($$$1 \leq i \leq n$$$) is said to be a local minimum if $$$a_i < \min\{a_{i-1},a_{i+1}\}$$$, where $$$a_0 = a_{n+1} = +\infty$$$. An array is said to be a permutation of integers $$$1$$$ to $$$n$$$, if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Initially, you are only given the value of $$$n$$$ without any other information about this permutation.At each interactive step, you are allowed to choose any $$$i$$$ ($$$1 \leq i \leq n$$$) and make a query with it. As a response, you will be given the value of $$$a_i$$$. You are asked to find any index $$$k$$$ which is a local minimum after at most $$$100$$$ queries.

NoteIn the example, the first line contains an integer $$$5$$$ indicating that the length of the array is $$$n = 5$$$.The example makes five "?" queries, after which we conclude that the array is $$$a = [3,2,1,4,5]$$$ and $$$k = 3$$$ is local minimum.

$stdout.sync = true

def query(x)
  puts "? #{x}"
  gets.chomp.to_i
end

def solution(n)
  value = yield(1)
  l, r = 1, value + 1
  while r - l > 1 do
    mid = (l + r) / 2
    a, b = yield(mid - 1), yield(mid)
    delta = mid - l
    if a < b
      r = mid
    elsif b <= value - delta
      l, value = mid, b
    else
      r = mid
    end
  end
  return l
end

def stress
  array = (20).times.map { |x| x + 1 }.shuffle
  index = solution(array.length) { |x| array[x - 1] } - 1
  puts(array.inspect)
  puts(index)
  if not ((index == 0 or array[index - 1] > array[index]) and (index == array.length - 1 or array[index + 1] > array[index]))
    puts("Fail!")
  end
end

def main
  n = gets.chomp.to_i
  puts("! #{solution(n) { |x| query(x) }}")
end

main

n=gets.to_i
arr=[nil]*(n+2)
l=0
r=n+1
while r-l>3
  m0=l+(r-l)/3
  m1=r-(r-l)/3
  if !arr[m0]
    puts "? #{m0}"
    $stdout.flush
    v0=gets.to_i
    arr[m0]=v0
  else
    v0=arr[m0]
  end
  if !arr[m1]
    puts "? #{m1}"
    $stdout.flush
    v1=gets.to_i
    arr[m1]=v1
  else
    v1=arr[m1]
  end
  if v0>v1
    l=m0
  else
    r=m1
  end
end
m0=l+1
m1=r-1
if !arr[m0]
  puts "? #{m0}"
  $stdout.flush
  v0=gets.to_i
  arr[m0]=v0
else
  v0=arr[m0]
end
if !arr[m1]
  puts "? #{m1}"
  $stdout.flush
  v1=gets.to_i
  arr[m1]=v1
else
  v1=arr[m1]
end
if v0>v1
  puts "! #{m1}"
else
  puts "! #{m0}"
end

$stdout.sync = true

def query(x)
  puts "? #{x}"
  gets.chomp.to_i
end

n = gets.chomp.to_i
value = query(1)
l, r = 1, value + 1
while r - l > 1 do
  mid = (l + r) / 2
  mid_value = query(mid)
  delta = mid - l
  if mid_value <= value - delta
    l, value = mid, mid_value
  else
    r = mid
  end
end
puts "! #{l}"

$stdout.sync = true

def query(x)
  puts "? #{x}"
  gets.chomp.to_i
end

n = gets.chomp.to_i
value = query(1)
l, r = 1, value + 1
while r - l > 1 do
  mid = (l + r) / 2
  mid_value = query(mid)
  delta = mid - l
  if mid_value <= value - delta
    l = mid
    value = mid_value
  else
    r = mid
  end
end
puts "! #{l}"

n=gets.to_i
l=1
r=n
ll=l
rr=r
puts "? #{l}"
$stdout.flush
lm=gets.to_i
puts "? #{r}"
$stdout.flush
rm=gets.to_i
while true
  m=(l+r)/2
  f=0
  if lm<=rm
    r=m
    f=0
  else
    l=m
    f=1
  end
  while r-l>1
    puts "? #{m}"
    $stdout.flush
    m=(l+r)/2
    if f==0
      rm=gets.to_i
    else
      lm=gets.to_i
    end
    if lm<=rm
      rr=r
      r=m
      f=0
    else
      ll=l
      l=m
      f=1
    end
  end
  puts "? #{m}"
  $stdout.flush
  mm=gets.to_i
  if lm>mm&&mm<rm
    puts "! #{m}"
    exit
  else
    l=ll
    r=rr
    puts "? #{l}"
    $stdout.flush
    lm=gets.to_i
    puts "? #{r}"
    $stdout.flush
    rm=gets.to_i
  end
end


Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level $$$n$$$ as a rooted tree constructed as described below.A rooted dead bush of level $$$1$$$ is a single vertex. To construct an RDB of level $$$i$$$ we, at first, construct an RDB of level $$$i-1$$$, then for each vertex $$$u$$$:   if $$$u$$$ has no children then we will add a single child to it;  if $$$u$$$ has one child then we will add two children to it;  if $$$u$$$ has more than one child, then we will skip it.   Rooted Dead Bushes of level $$$1$$$, $$$2$$$ and $$$3$$$. Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:  The center of the claw is the vertex with label $$$1$$$. Lee has a Rooted Dead Bush of level $$$n$$$. Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $$$10^9+7$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^6$$$) — the level of Lee's RDB.

For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo $$$10^9 + 7$$$.

NoteIt's easy to see that the answer for RDB of level $$$1$$$ or $$$2$$$ is $$$0$$$.The answer for RDB of level $$$3$$$ is $$$4$$$ since there is only one claw we can choose: $$$\{1, 2, 3, 4\}$$$.The answer for RDB of level $$$4$$$ is $$$4$$$ since we can choose either single claw $$$\{1, 3, 2, 4\}$$$ or single claw $$$\{2, 7, 5, 6\}$$$. There are no other claws in the RDB of level $$$4$$$ (for example, we can't choose $$$\{2, 1, 7, 6\}$$$, since $$$1$$$ is not a child of center vertex $$$2$$$).  Rooted Dead Bush of level 4.


Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1, r1], [l2, r2], ..., [ln, rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1, rn].

The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1 ≤ n ≤ 100, 0 ≤ P1, P2, P3 ≤ 100, 1 ≤ T1, T2 ≤ 60). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0 ≤ li < ri ≤ 1440, ri < li + 1 for i < n), which stand for the start and the end of the i-th period of work.

n, p1, p2, p3, t1, t2 = gets.split.map(&:to_i)
s, t = 0, 0
n.times do |i|
	l, r = gets.split.map(&:to_i)
	if i > 0
		[[p1, t1], [p2, t2], [p3, 1e9]].each do |pi, ti|
			d = [ti, l - t].min
			s += d * pi
			t += d
		end
	end
	s += (r - l) * p1
	t = r
end
p s

input=gets.split.map(&:to_i)
n=input[0]
p1=input[1]
p2=input[2]
p3=input[3]
t1=input[4]
t2=input[5]

back=-1
ans=0
n.times{|i|
    input=gets.split.map(&:to_i)
    if back==-1 then
        back=input[0]
    end
    ans+=(input[1]-input[0])*p1
    t=input[0]-back
    t1.times{
        if t==0 then
            break
        end
        t-=1
        ans+=p1
    }
    t2.times{
        if t==0 then
            break
        end
        t-=1
        ans+=p2
    }
    ans+=t*p3
    back=input[1]
}
puts ans

fst=gets.split
n=fst[0].to_i
p1=fst[1].to_i
p2=fst[2].to_i
p3=fst[3].to_i
t1=fst[4].to_i
t2=fst[5].to_i
line=gets.split
l=[line[0].to_i]
r=[line[1].to_i]
d=r[0]-l[0]
res=d*p1
(n-1).times do |i|
  line=gets.split
  l[i+1]=line[0].to_i
  r[i+1]=line[1].to_i
  d0=r[i+1]-l[i+1]
  res += d0*p1
  d1=l[i+1]-r[i]
  if d1<=t1
    res += d1*p1
  else
    res += t1*p1
    d2=d1-t1
    if d2<=t2
      res += d2*p2
    else
      res += t2*p2
      res += (d2-t2)*p3
    end
  end
end
puts res

s,e,c=[],[],0
n,p0,p1,p2,t0,t1=gets.chomp!.split(" ").map{|elem|elem.to_i}
n.times {|i|
  s[i%2],e[i%2]=gets.chomp!.split(" ").map{|elem|elem.to_i}
  c+=(e[i%2]-s[i%2])*p0
  if i>0 then w=s[i%2]-e[(i+1)%2]
  if w<=t0 then c+=w*p0 elsif w<=t0+t1 then c+=p0*t0+p1*(w-t0) else c+=p0*t0+p1*t1+p2*(w-t1-t0) end end
}
puts c

n, p1, p2, p3, t1, t2 = gets.chomp.split.map(&:to_i)
l, r = [], []
power = 0
n.times do |index|
	l[index % 2], r[index % 2] = gets.chomp.split.map(&:to_i)
	power += (r[index % 2] - l[index % 2]) * p1
	if index > 0
		no_activity = l[index % 2] - r[(index + 1) % 2]
		if no_activity <= t1
			power += no_activity * p1
		elsif no_activity <= t1 + t2
			power += t1 * p1 + (no_activity - t1) * p2
		else
			power += t1 * p1 + t2 * p2 + (no_activity - t1 - t2) * p3
		end
	end
end

puts power

s,e,c=[],[],0
n,p0,p1,p2,t0,t1=gets.chomp!.split(" ").map{|elem|elem.to_i}
n.times {|i|s[i%2],e[i%2]=gets.chomp!.split(" ").map{|elem|elem.to_i}
  c+=(e[i%2]-s[i%2])*p0
  if i>0 then w=s[i%2]-e[(i+1)%2]
  if w<=t0 then c+=w*p0 elsif w<=t1 then c+=p0*t0+p1*(w-t0) else c+=p0*t0+p1*t1+p2*(w-t1-t0) end end}
puts c


There are $$$n$$$ bricks numbered from $$$1$$$ to $$$n$$$. Brick $$$i$$$ has a weight of $$$a_i$$$.Pak Chanek has $$$3$$$ bags numbered from $$$1$$$ to $$$3$$$ that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick.After Pak Chanek distributes the bricks, Bu Dengklek will take exactly one brick from each bag. Let $$$w_j$$$ be the weight of the brick Bu Dengklek takes from bag $$$j$$$. The score is calculated as $$$|w_1 - w_2| + |w_2 - w_3|$$$, where $$$|x|$$$ denotes the absolute value of $$$x$$$.It is known that Bu Dengklek will take the bricks in such a way that minimises the score. What is the maximum possible final score if Pak Chanek distributes the bricks optimally?

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the number of bricks. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the weights of the bricks. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a line containing an integer representing the maximum possible final score if Pak Chanek distributes the bricks optimally.

NoteIn the first test case, one way of achieving a final score of $$$6$$$ is to do the following:   Put bricks $$$1$$$, $$$4$$$, and $$$5$$$ into bag $$$1$$$.  Put brick $$$3$$$ into bag $$$2$$$.  Put brick $$$2$$$ into bag $$$3$$$. If Pak Chanek distributes the bricks that way, a way Bu Dengklek can take the bricks is:   Take brick $$$5$$$ from bag $$$1$$$.  Take brick $$$3$$$ from bag $$$2$$$.  Take brick $$$2$$$ from bag $$$3$$$. The score is $$$|a_5 - a_3| + |a_3 - a_2| = |3 - 5| + |5 - 1| = 6$$$. It can be shown that Bu Dengklek cannot get a smaller score from this distribution.It can be shown that there is no other distribution that results in a final score bigger than $$$6$$$.

t=gets.to_i
t.times do
    n=gets.to_i
    arr=gets.chomp.split(' ').map(&:to_i)
    arr.sort!
    r=0
    (2..(n-2)).each do|x|
        r=[r, arr[x]-arr[0]+arr[x]-arr[x-1], arr[x]-arr[x-1]+arr[-1]-arr[x-1]].max
    end
    r=[r, arr[1]-arr[0]+arr[-1]-arr[0],arr[-1]-arr[-2]+arr[-1]-arr[0]].max
    puts r
end

t=gets.to_i
t.times do
    n=gets.to_i
    arr=gets.chomp.split(' ').map(&:to_i)
    arr.sort!
    puts arr[-1]-arr[0]+[arr[1]-arr[0],arr[-1]-arr[-2]].max
end


Turbulent times are coming, so you decided to buy sugar in advance. There are $$$n$$$ shops around that sell sugar: the $$$i$$$-th shop sells one pack of sugar for $$$a_i$$$ coins, but only one pack to one customer each day. So in order to buy several packs, you need to visit several shops.Another problem is that prices are increasing each day: during the first day the cost is $$$a_i$$$, during the second day cost is $$$a_i + 1$$$, during the third day — $$$a_i + 2$$$ and so on for each shop $$$i$$$.On the contrary, your everyday budget is only $$$x$$$ coins. In other words, each day you go and buy as many packs as possible with total cost not exceeding $$$x$$$. Note that if you don't spend some amount of coins during a day, you can't use these coins during the next days.Eventually, the cost for each pack will exceed $$$x$$$, and you won't be able to buy even a single pack. So, how many packs will you be able to buy till that moment in total?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ cases follow. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le x \le 10^9$$$) — the number of shops and your everyday budget. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial cost of one pack in each shop. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the total number of packs you will be able to buy until prices exceed your everyday budget.

NoteIn the first test case,   Day 1: prices are $$$[2, 1, 2]$$$. You can buy all $$$3$$$ packs, since $$$2 + 1 + 2 \le 7$$$.  Day 2: prices are $$$[3, 2, 3]$$$. You can't buy all $$$3$$$ packs, since $$$3 + 2 + 3 > 7$$$, so you buy only $$$2$$$ packs.  Day 3: prices are $$$[4, 3, 4]$$$. You can buy $$$2$$$ packs with prices $$$4$$$ and $$$3$$$.  Day 4: prices are $$$[5, 4, 5]$$$. You can't buy $$$2$$$ packs anymore, so you buy only $$$1$$$ pack.  Day 5: prices are $$$[6, 5, 6]$$$. You can buy $$$1$$$ pack.  Day 6: prices are $$$[7, 6, 7]$$$. You can buy $$$1$$$ pack.  Day 7: prices are $$$[8, 7, 8]$$$. You still can buy $$$1$$$ pack of cost $$$7$$$.  Day 8: prices are $$$[9, 8, 9]$$$. Prices are too high, so you can't buy anything.  In total, you bought $$$3 + 2 + 2 + 1 + 1 + 1 + 1 = 11$$$ packs.In the second test case, prices are too high even at the first day, so you can't buy anything.In the third test case, you can buy only one pack at day one.In the fourth test case, you can buy $$$2$$$ packs first $$$500$$$ days. At day $$$501$$$ prices are $$$[501, 501]$$$, so you can buy only $$$1$$$ pack the next $$$500$$$ days. At day $$$1001$$$ prices are $$$[1001, 1001]$$$ so can't buy anymore. In total, you bought $$$500 \cdot 2 + 500 \cdot 1 = 1500$$$ packs.

gets.to_i.times do
  n, x = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i).sort
  sums = as.reduce([]) { |acc, x| acc << (acc.last || 0) + x }
  answer = sums.map.with_index do |sum, i|
    [0, (1 + (x - sum) / (i + 1))].max
  end.sum
  p answer
end

gets.to_i.times do
  n, x= gets.chomp.split.map(&:to_i)
  a = gets.chomp.split.map(&:to_i).sort
  cum = 0
  ans = 0
  0.upto(n-1) do |i|
    cum += a[i]
    ans += (x >= cum)?((x-cum)/(i+1)+1) : 0
  end
  puts ans
end


While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.To represent the string as a number in numeral system with base 64 Vanya uses the following rules:  digits from '0' to '9' correspond to integers from 0 to 9;  letters from 'A' to 'Z' correspond to integers from 10 to 35;  letters from 'a' to 'z' correspond to integers from 36 to 61;  letter '-' correspond to integer 62;  letter '_' correspond to integer 63.

The only line of the input contains a single word s (1 ≤ |s| ≤ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.

Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7.

NoteFor a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions:   z&_ = 61&63 = 61 = z  _&z = 63&61 = 61 = z  z&z = 61&61 = 61 = z

 def gao(ch)
  case ch
  when '0'..'9'
    return ch.ord - '0'.ord
  when 'A'..'Z'
    return ch.ord - 'A'.ord + 10
  when 'a'..'z'
    return ch.ord - 'a'.ord + 36
  when '-'
    return 62
  when '_'
    return 63
  end
end

def cal(num)
#  puts num
  ret = 0
  6.times do
    ret += 1 if (num % 2) == 0
    num >>= 1
  end
#  puts ret
  ret
end

str = readline.strip
sum = str.each_char.map{|num| gao(num)}.map{|num| cal(num)}.inject(0, :+)
mod = 1000000007
res = 1
sum.times {res = (res * 3) % mod}
puts res

s = gets.chomp
ans = 1
patterns = ("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a + ["-","_"]
symbols = {}
patterns.each_with_index do |s,i|
    symbols[s] = i
end

for c in s.split("") do
    val = symbols[c]
    6.times do |i|
        if val&1 == 0 then
            ans = (ans*3)%1000000007
        end
        val >>= 1
    end
end

print ans

s = gets.chomp

mod = 10**9 + 7
str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'
ans = 1

s.split('').each do |c|
  (str.index(c) + 64).to_s(2).split('').each do |d|
    ans = ans * 3 % mod if d == '0'
  end
end

puts ans


An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.

A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.

In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other. In the second line print k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai - ai + 1| ≠ 1 for all i from 1 to k - 1. If there are several possible answers, output any of them.

#!/usr/bin/env ruby
n=gets.to_i
if n<3
	puts "1\n1\n"
elsif n<4
	puts "2\n1 3\n"
else
	p n
	puts (2.step(n,2).to_a+1.step(n,2).to_a)*' '
end

# http://codeforces.com/contest/534/problem/A
n = gets.to_i
arr = case n
      when 1, 2
        [1]
      when 3
        [1, 3]
      else
        2.step(n, 2).to_a + 1.step(n, 2).to_a
      end

puts arr.length
puts arr.join(' ')

a=gets.chomp.to_i
if a==1
puts "1"
puts "1"
elsif a==2
puts "1"
puts "1"
elsif a==3
puts "2"
puts "1 3"
else
puts "#{a}"
if a%2==1
printf "#{a/2 + 1} "
0.upto(a/2 - 1) do |i|
printf "#{i+1} #{a-i} "
end
else
printf "#{a/2 + 1} "
0.upto(a/2 - 2) do |i|
printf "#{i+1} #{a-i} "
end
printf "#{a/2}"
end
end

n=gets.to_i
arr=[]
if n<5 then
	arr=[[],[1],[1],[1,3],[2,4,1,3]][n]
	puts arr.size
	puts arr*" "

else
	1.step(n,2){|e|
			arr<<e
	}
	2.step(n,2){|e|
		arr<<e
	}
	puts arr.size
	puts arr*" "
end

n = gets.to_i

if n == 1 || n == 2
  puts '1'
  puts '1'
elsif n == 3
  puts '2'
  puts '1 3'
else
  puts n

  print 3
  (5..n).step(2).each_with_index { |v,i|
    print ' '
    print v
  }
  print ' '
  print 1
  (2..n).step(2).each_with_index.reverse_each { |v, i|
    print ' '
    print v
  }
  print "\n"
end

def sol(arr,i,n)
	# p arr
	if i>n
		return arr
	end

	ch = 0
	if !arr.include?(i)
		if arr == []
			ch = 1
			p = sol(arr+[i],1,n)
		elsif (i>=arr[-1]+2 || i<=arr[-1]-2)
			ch = 1
			p = sol(arr+[i],1,n)
		end
	end
	np = sol(arr,i+1,n)

	if ch == 1
		return p.length > np.length ? p : np
	end
	return np
end

n = gets.chomp.to_i
f = (1..n/2).to_a.reverse
bf = ((n/2)+1..n).to_a.reverse
order = f.length>bf.length ? 1 : 2

if n < 6
	a = sol([],1,n)
	puts "#{a.length}"
	puts a.join(" ")
else

	ans = []
	while true
		if f == [] && bf == []
			break
		end
		if order == 1
			if f!=[]
				ans << f.pop
			end
			if bf!=[]
				ans << bf.pop
			end
		else
			if bf!=[]
				ans << bf.pop
			end
			if f!=[]
				ans << f.pop
			end
		end
	end

	puts "#{ans.length}"

	puts ans.join(" ")
end

n = gets.strip.to_i
if n <= 2
  puts "1"
  puts "1"
  exit
end

if n == 3
  puts n - 1
  puts (1..n).to_a.select { |e| e.odd? }.sort.reverse.join(' ')
  exit
end

odd = (1..n).to_a.select { |e| e.odd? }.sort.reverse
even = (1..n).to_a.select { |e| e.even? }.sort.reverse

puts n
print odd.join(' ')
print " "
print even.join(' ')

a= gets().chomp().to_i
if a==1||a==2
  print 1,"\n",1
elsif a==3
  print 2,"\n",1,' ',3
else
 print a,"\n" ;(1..a).each{|num| print num,' ' if num%2==0} ;(1..a).each{|num| print num,' ' if num%2==1}
end

n = gets.to_i

if n <= 2
  puts "1\n1\n"
elsif n == 3
  puts "2\n1 3\n"
else
  e = 1.upto(n).select { |x| x % 2 == 0 }
  o = 1.upto(n).select { |x| x % 2 == 1 }
  puts n
  puts e.join(" ") + " " + o.join(" ")
end

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
elsif n==3
    print "2\n1 3\n"
    exit
elsif n==4
    print "4\n3 1 4 2\n"
    exit
end
left = Array.new
right = Array.new
for i in (1...n).step(2)
    left.push(i)
    right.push(i+1)
end
if n.odd?
    left.push(n)
end
puts n
puts (left+right).join(' ')

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
elsif n==3
    print "2\n1 3\n"
    exit
elsif n==4
    print "4\n3 1 4 2\n"
    exit
end
puts n
puts ((1..n).step(2).to_a+(2..n).step(2).to_a).join(' ')

n = gets.to_i
ans = case n
when 1, 2
  [1]
when 3
  [1, 3]
when 4
  [3, 1, 4, 2]
else
  a = []
  b = []
  1.upto(n) do |i|
    (i.odd? ? a : b) << i
  end
  a + b
end
puts ans.size
puts ans.join(" ")

n = gets.to_i
a = case n
when 1, 2
  [1]
when 3
  [1, 3]
when 4
  [3, 1, 4, 2]
else
  a = []
  b = []
  n.times do |i|
    i += 1
    (i % 2 == 0 ? b : a) << i
  end
  a + b
end
puts a.size
puts a.join(" ")

n = gets.to_i
ans = case n
when 1, 2
  [1]
when 3
  [1, 3]
when 4
  [3, 1, 4, 2]
else
  (1..n).partition{|x| x.odd?}.flatten
end
puts ans.size, ans.join(" ")

#!/usr/bin/env ruby
n=gets.to_i
if n<3
	puts "1\n1\n"
elsif n<5
	puts "2\n1 3\n"
else
	p n
	puts (1.step(n,2).to_a+2.step(n,2).to_a)*' '
end

# http://codeforces.com/contest/534/problem/A
n = gets.to_i
arr = case n
      when 1, 2
        [1]
      when 3
        [1, 3]
      else
        1.step(n, 2).to_a + 2.step(n, 2).to_a
      end

puts arr.length
puts arr.join(' ')

a=gets.chomp.to_i
if a==1
puts "1"
puts "1"
elsif a==2
puts "0"
elsif a==3
puts "2"
puts "1 3"
else
puts "#{a}"
if a%2==1
printf "#{a/2 + 1} "
0.upto(a/2 - 1) do |i|
printf "#{i+1} #{a-i} "
end
else
printf "#{a/2 + 1} "
0.upto(a/2 - 2) do |i|
printf "#{i+1} #{a-i} "
end
printf "#{a/2}"
end
end

n = gets.to_i

if n == 2
  pust '1'
  puts '1'
elsif n == 3
  puts '2'
  puts '1 3'
else
  puts n

  print 3
  (5..n).step(2).each_with_index { |v,i|
    print ' '
    print v
  }
  print ' '
  print 1
  (2..n).step(2).each_with_index.reverse_each { |v, i|
    print ' '
    print v
  }
  print "\n"
end

def sol(arr,i,n)
	# p arr
	if i>n
		return arr
	end

	ch = 0
	if !arr.include?(i)
		if arr == []
			ch = 1
			p = sol(arr+[i],1,n)
		elsif (i>=arr[-1]+2 || i<=arr[-1]-2)
			ch = 1
			p = sol(arr+[i],1,n)
		end
	end
	np = sol(arr,i+1,n)

	if ch == 1
		return p.length > np.length ? p : np
	end
	return np
end

n = gets.chomp.to_i
f = (1..n/2).to_a.reverse
bf = ((n/2)+1..n).to_a.reverse

if n < 6
	a = sol([],1,n)
	puts "#{a.length}"
	puts a.join(" ")
else

	ans = []
	while true
		if f == [] && bf == []
			break
		end
		if f!=[]
			ans << f.pop
		end
		if bf!=[]
			ans << bf.pop
		end
	end

	puts "#{ans.length}"

	puts ans.join(" ")
end

# def sol(arr,i,n)
# 	# p arr
# 	if i>n
# 		return arr
# 	end

# 	ch = 0
# 	if !arr.include?(i)
# 		if arr == []
# 			ch = 1
# 			p = sol(arr+[i],1,n)
# 		elsif (i>=arr[-1]+2 || i<=arr[-1]-2)
# 			ch = 1
# 			p = sol(arr+[i],1,n)
# 		end
# 	end
# 	np = sol(arr,i+1,n)

# 	if ch == 1
# 		return p.length > np.length ? p : np
# 	end
# 	return np
# end

n = gets.chomp.to_i
an = [1]
set = (2..n).to_a
i = 0
while true
	if n == 4
		break
	end
	ch = 0
	if i == n
		break
	end
	set.length.times{|x|
		if set[x]>=an[i]+2 || set[x] <= an[i]-2
			# p set
			an<< set[x]
			set.delete(set[x])
			i+=1
			ch = 1
			break
		end
	}
	if ch == 0
		break
	end
end

if n == 4
	puts 4.to_s
	puts [3,1,4,2].join(" ")
else
	# a = sol([],1,n)
	puts "#{i}"
	# puts "#{a.length}"
	# puts a.join(" ")
	puts an.join(" ")
end

n = gets.chomp.to_i
an = [1]
set = (2..n).to_a
i = 0
while true
	ch = 0
	if i == n
		break
	end
	set.length.times{|x|
		if set[x]>=an[i]+2 || set[x] <= an[i]-2
			# p set
			an<< set[x]
			set.delete(set[x])
			i+=1
			ch = 1
			break
		end
	}
	if ch == 0
		break
	end
end

puts "#{i+1}"
puts an.join(" ")

# def sol(arr,i,n)
# 	# p arr
# 	if i>n
# 		return arr
# 	end

# 	ch = 0
# 	if !arr.include?(i)
# 		if arr == []
# 			ch = 1
# 			p = sol(arr+[i],1,n)
# 		elsif (i>=arr[-1]+2 || i<=arr[-1]-2)
# 			ch = 1
# 			p = sol(arr+[i],1,n)
# 		end
# 	end
# 	np = sol(arr,i+1,n)

# 	if ch == 1
# 		return p.length > np.length ? p : np
# 	end
# 	return np
# end

n = gets.chomp.to_i
an = [1]
set = (2..n).to_a
i = 0
while true
	if n == 4
		break
	end
	ch = 0
	if i == n
		break
	end
	set.length.times{|x|
		if set[x]>=an[i]+2 || set[x] <= an[i]-2
			# p set
			an<< set[x]
			set.delete(set[x])
			i+=1
			ch = 1
			break
		end
	}
	if ch == 0
		break
	end
end

if n == 4
	puts 4.to_s
	puts [3,1,4,2].join(" ")
else
	# a = sol([],1,n)
	puts "#{i+1}"
	# puts "#{a.length}"
	# puts a.join(" ")
	puts an.join(" ")
end

n = gets.strip.to_i
if n <= 2
  puts "0"
  exit
end

if n == 3
  puts n - 1
  puts (1..n).to_a.select { |e| e.odd? }.sort.join(' ')
  exit
end
odd = (1..n).to_a.select { |e| e.odd? }.sort
even = (1..n).to_a.select { |e| e.even? }.sort

puts n
print odd.join(' ')
print " "
print even.join(' ')

n = gets.strip.to_i
if n <= 2
  puts "1"
  puts "1"
  exit
end

if n == 3
  puts n - 1
  puts (1..n).to_a.select { |e| e.odd? }.sort.join(' ')
  exit
end
odd = (1..n).to_a.select { |e| e.odd? }.sort
even = (1..n).to_a.select { |e| e.even? }.sort

puts n
print odd.join(' ')
print " "
print even.join(' ')

n = gets.strip.to_i
if n <= 2
  puts "0"
  exit
end

if n == 3
  puts (1..n).to_a.select { |e| e.odd? }.sort.join(' ')
  exit
end
odd = (1..n).to_a.select { |e| e.odd? }.sort
even = (1..n).to_a.select { |e| e.even? }.sort

print odd.join(' ')
print " "
print even.join(' ')

n = gets.to_i
if n==1
    print "1\n1\n"
    exit
end
left = Array.new
right = Array.new
k = n/2
for i in 1..k
    if i.odd?
        left.push(i)
        right.push(n+1-i)
    else
        left.push(n+1-i)
        right.push(i)
    end
end
puts k*2
puts (left+right).join(' ')

n = gets.to_i
left = Array.new
right = Array.new
k = n/2
for i in 1..k
    if i.odd?
        left.push(i)
        right.push(n+1-i)
    else
        left.push(n+1-i)
        right.push(i)
    end
end
puts k*2
puts (left+right).join(' ')

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
elsif n==3
    print "2\n1 3\n"
    exit
elsif n==4
    print "4\n1 4 2 3\n"
    exit
end
left = Array.new
right = Array.new
for i in (1...n).step(2)
    left.push(i)
    right.push(i+1)
end
if n.odd?
    left.push(n)
end
puts n
puts (left+right).join(' ')

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
elsif n==4
    print "4\n3 1 4 2\n"
end
left = Array.new
right = Array.new
k = n/2
for i in 1..k
    if i.odd?
        left.push(i)
        right.push(n+1-i)
    else
        left.push(n+1-i)
        right.push(i)
    end
end
puts k*2
puts (left+right).join(' ')

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
end
left = Array.new
right = Array.new
k = n/2
for i in 1..k
    if i.odd?
        left.push(i)
        right.push(n+1-i)
    else
        left.push(n+1-i)
        right.push(i)
    end
end
puts k*2
puts (left+right).join(' ')

n = gets.to_i
if n==1 or n==2
    print "1\n1\n"
    exit
elsif n==4
    print "4\n3 1 4 2\n"
    exit
end
left = Array.new
right = Array.new
k = n/2
for i in 1..k
    if i.odd?
        left.push(i)
        right.push(n+1-i)
    else
        left.push(n+1-i)
        right.push(i)
    end
end
puts k*2
puts (left+right).join(' ')