Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.

If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.

NoteHere is the representation of the graph from the first example:

N, M = gets.split.map(&:to_i)
if N-1 > M
    puts 'Impossible'
    exit
end

$ans = []
(2..N).each do |i|
    $ans.push([1, i])
end

def coprimes(a, b)
    d = a+b
    while d <= N
        $ans.push([b, d]) if b.between?(2, N) && d.between?(2, N)
        if $ans.length == M
            puts 'Possible'
            $ans.each do |arr|
                puts arr.join(' ')
            end
            exit
        end
        coprimes(b, d)
        d += b
    end
end

coprimes(1, 1)
puts 'Impossible'

def gcd(a, b)
  return a if b == 0
  gcd(b, a%b)
end

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

if m<n-1
  puts "Impossible"
  exit 0
end

u = 1
v = 2
possible = true
edges = []
m.times do
  while u<=n && u<v && v<=n && gcd(u,v) > 1
    v += 1
    if v > n
      u += 1
      v = u + 1
    end
  end
  if u<=n && u<v && v<=n
    edges << [u, v]
    v += 1
    if v > n
      u += 1
      v = u + 1
    end
  else
    possible = false
    break
  end
end

if possible
  puts "Possible"
  edges.each do |e|
    puts e.join(' ')
  end
else
  puts "Impossible"
end

N, M = gets.split.map(&:to_i)
if N-1 > M
    puts 'Impossible'
    exit
end

$ans = []
(2..N).each do |i|
    $ans.push([1, i])
end

def coprimes(a, b)
    d = a+b
    while d <= N
        $ans.push([b, d]) if a.between?(2, N) && b.between?(2, N)
        if $ans.length == M
            puts 'Possible'
            $ans.each do |arr|
                puts arr.join(' ')
            end
            exit
        end
        coprimes(b, d)
        d += b
    end
end

coprimes(1, 1)
puts 'Impossible'

N, M = gets.split.map(&:to_i)
if N-1 > M
    puts 'Impossible'
    exit
end

$ans = []

def coprimes(a, b)
    d = a+b
    while d <= N
        $ans.push([b, d]) if a.between?(1, N) && b.between?(1, N)
        if $ans.length == M
            puts 'Possible'
            $ans.each do |arr|
                puts arr.join(' ')
            end
            exit
        end
        coprimes(b, d)
        d += b
    end
end

coprimes(1, 1)
puts 'Impossible'


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

gets;a=gets.split.map &:to_i;b=gets.split.map &:to_i;z=[a.min*2,a.max].max;p z<b.min ? z:-1

s1 = (gets.chomp).split
n = s1[0]
m = s1[1]
a1 =  (gets.chomp).split.collect{|i| i.to_i}
a2 =  (gets.chomp).split.collect{|i| i.to_i}
extra = a1.min
max = a1.max
min = a2.min
if !(2*extra < min)
  p -1
elsif !(max<min)
  p -1
elsif (2*extra < max)
  p max
else
  p 2*extra
end

#!/usr/bin/ruby

n, m = $stdin.readline.split.map(&:to_i)
ni = $stdin.readline.split.map(&:to_i)
mi = $stdin.readline.split.map(&:to_i)

nmin = ni.min
nmax = ni.max
mmin = mi.min

101.times { |i|
  if (nmin * 2 <= i) && (nmax <= i) && (mmin > i)
    puts i
    exit
  end
}

puts -1

nr, nw = gets.split.map{|s| s.to_i}
rst = gets.split.map{|s| s.to_i}
wst = gets.split.map{|s| s.to_i}
rst_min = rst.min
rst_max = rst.max
wst_min = wst.min
wst_max = wst.max
if wst_min <= rst_max || wst_min <= rst_min*2
	puts -1
else
	puts [rst_max, rst_min*2].max
end

n,m=gets.chomp.split.map(&:to_i);a=gets.chomp.split.map(&:to_i);b=gets.chomp.split.map(&:to_i)
v,p,c=a.min,a.max,b.min
x=[2*v,p].max
puts (x<c)? x : "-1"

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

arr=Array.new
arr2=Array.new

arr1=gets.split(" ").map { |i| i.to_i}.take(n)
arr2=gets.split(" ").map { |i| i.to_i}.take(m)

if [2*arr1.min,arr1.max].max < arr2.min
	print [2*arr1.min, arr1.max ].max
else
	print -1
end

class A
  def initialize
    n, m = gets.chomp.split(' ').map(&:to_i)

    correct = gets.chomp.split(' ').map(&:to_i).sort
    wrong = gets.chomp.split(' ').map(&:to_i).sort

    tl = [correct.first * 2, correct.last].max

    if tl < wrong.first
      puts [correct.first * 2, correct.last].max
    else
      puts -1
    end
  end
end

a = A.new

gets
a = gets.chomp.split(/ /).map(&:to_i)
b = gets.chomp.split(/ /).map(&:to_i)
v = a.min
p = a.max
c = b.min
if [2 * v, p].max < c
    puts [2 * v, p].max
else
    puts "-1"
end

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

res=-1
1.upto(b[0]-1) {|v|
    extra=false
    ok=true
    a.each {|w|
        extra=true if w*2<=v
        ok=false if w>v
    }
    if ok and extra then
        res=v
        break
    end
}
p res

n,m = gets.split(" ").map(&:to_i)
correct = gets.split(" ").map(&:to_i)
wrong = gets.split(" ").map(&:to_i)
start = correct.max
finish = wrong.min - 1
tl = -1
(start..finish).each { |v|
	if correct.any?{|a| 2 * a <= v }
		tl = v
		break
	end
}
puts tl

n, m = gets.chomp.to_i
a = gets.chomp.split.collect{|i| i.to_i}
b = gets.chomp.split.collect{|i| i.to_i}

a_min = a.sort[0]
tl = b.sort[0] - 1
if a.any?{|i| i * 2 <= tl }
  if ans = (a.sort[-1]..tl).select{|i| a_min * 2 <= i }[0]
    puts ans
  else
    puts -1
  end
else
  puts -1
end

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

correct.sort!
wrong.sort!

ans = [2 * correct[0], correct[n - 1]].max

if ans >= wrong[0]
    puts -1
else
    puts ans
end

gets
a=gets.split.map{|s|s.to_i}
b=gets.split.map{|s|s.to_i}
m=[2*a.min,a.max].max
puts (m<b.min)?m: -1

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

arr=Array.new
arr2=Array.new

arr1=gets.split(" ").map { |i| i.to_i}.take(n)
arr2=gets.split(" ").map { |i| i.to_i}.take(m)

if arr1.min*2 <= arr1.max && arr1.max<arr2.min
	print arr1.max
else
	print -1
end

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

arr=Array.new
arr2=Array.new

arr1=gets.split(" ").map { |i| i.to_i}.take(n)
arr2=gets.split(" ").map { |i| i.to_i}.take(m)

if arr1.min*2 <= arr1.max && arr1.max<arr2.max
	print arr1.max
else
	print -1
end

n, m = gets.chomp.to_i
a = gets.chomp.split.collect{|i| i.to_i}
b = gets.chomp.split.collect{|i| i.to_i}

a_min = a.sort[0]
tl = b.sort[0] - 1
if a.any?{|i| i * 2 <= tl }
  puts (a.sort[-1]..tl).select{|i| a_min * 2 <= i }[0]
else
  puts -1
end

n, m = gets.chomp.to_i
a = gets.chomp.split.collect{|i| i.to_i}
b = gets.chomp.split.collect{|i| i.to_i}

tl = b.sort[0] - 1
if a.any?{|i| i * 2 <= tl }
  puts tl.to_i
else
  puts -1
end

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

correct.sort!
wrong.sort!

ans = correct[n - 1]

if ans >= wrong[0] || 2 * correct[0] > ans
    puts -1
else
    puts ans
end

gets
a=gets.split.map{|s|s.to_i}
b=gets.split.map{|s|s.to_i}
if a.size>1
puts (2*a.min<=a.max&&a.max<b.min)?a.max: -1
else
puts (2*a[0]<b.min)?2*a[0]: -1
end

gets
a=gets.split.map{|s|s.to_i}
b=gets.split.map{|s|s.to_i}
puts (2*a.min<=a.max&&a.max<b.min)?a.max: -1


Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.  Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.

Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).

NoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.

n = readline.to_i
str = readline.strip
arr = readline.split(' ').collect(&:to_i)
hash = Hash.new(true)
hash[0] = true
now = 0
while true
  now = now + arr[now] * (str[now] == ">" ? 1 : -1)
  if now >= n || now < 0 || hash.has_key?(now)
    break
  end
  hash[now] = true
end
if now >= n || now < 0
  puts "FINITE"
else
  puts "INFINITE"
end

require 'set'

strip_length = gets.chomp.to_i

Jump = Struct.new(:direction, :length)
jumps = []
a = gets.chomp
b = gets.chomp.split(' ')

for i in 0..a.length-1
	jumps[i] = Jump.new(a[i], b[i].to_i)
end

visited = Set.new
x = 0

loop {
	visited.add(x)
	dir = jumps[x].direction == ">" ? 1 : -1
	x += dir * jumps[x].length
	if x >= jumps.length || x < 0
		puts "FINITE"
		break
	end

	if visited.include?(x)
		puts "INFINITE"
		break
	end

}

l = gets.to_i
dirs = gets.to_s
nums = gets.split(' ').map { |i| i.to_i }
ex = false
next_pos = 1
dirs.length.times { |i|
  n = dirs[next_pos-1]
  next_pos = (n == '>' ? next_pos + nums[next_pos-1] : next_pos - nums[next_pos-1])
  if next_pos > l or next_pos <= 0
    ex = true
    break
  end
}
puts ex ? 'FINITE' : 'INFINITE'

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

FIN = 'FINITE'
INF = 'INFINITE'

n = gi
j = gs.each_char.to_a
d = gis

jp = n.times.map{|i| j[i] == "<" ? -d[i] : d[i]}

f = [false] * jp.size

i = 0

loop {
    if f[i]
        puts INF
        exit
    end
    f[i] = true
    i += jp[i]
    if i < 0 || i > n - 1
        puts FIN
        exit
    end
}

a=gets.chomp.to_i
b=gets.chomp.split("")
c=gets.chomp.split(" ").map{|i| i.to_i}
d=Array.new(a,1)

cur=0
d[0]=0
trig=1
loop do
if b[cur]==">"
cur+=c[cur]
break if cur>=a || cur<0
if d[cur]==0
trig=0
break
else
d[cur]=0
end
end
if b[cur]=="<"
cur-=c[cur]
break if cur>=a || cur<0
if d[cur]==0
trig=0
break
else
d[cur]=0
end
end
end

if trig==1
puts "FINITE"
else
puts "INFINITE"
end

n = gets.to_i
s = gets
values = gets.split.map{|x| x.to_i}
vis = Array.new(n , false)

i = 0
flag = false

while (vis[i] == false)

	vis[i] = true

	if(s[i] == '>')
		i += values[i]
	else
		i -= values[i]

	end

	if(i < 0 || i >= s.length - 1)
		flag = true
		break
	end
end

puts "FINITE" if flag == true
puts "INFINITE" if flag == false

n = gets.chomp.to_i

direcs = gets.chomp.split("")
lens = gets.chomp.split(" ").map(&:to_i)

a = Array.new(n, 0)

curr = 0
while curr >= 0 && curr < n
  if a[curr] != 0
    puts "INFINITE"
    exit
  end
  a[curr] = 1
  if direcs[curr] == "<" then
    move = lens[curr] * -1
  else
    move = lens[curr]
  end
  curr += move
end
puts "FINITE"

n = gets.to_i
map = gets.chomp
len = gets.chomp.split(' ')
len.each_index { |i| len[i] = len[i].to_i }

cnt = Array.new(len.size) { |e| e = 0 }
pos, loo = 0, false

while true
  cnt[pos] += 1
  if cnt[pos] == 2
    loo = true
    break
  end
  if map[pos] == '>'
    npos = pos + len[pos]
  else
    npos = pos - len[pos]
  end
  if npos > n-1 or npos < 0 #out of range
    loo = false
    break
  end
  pos = npos
end

if loo
  puts "INFINITE"
else
  puts "FINITE"
end

n = gets.to_i
dir = gets
jlen = gets.split.map{|x| x.to_i}
used = Array.new(n, false)

(dir.length-1).times do |i|
  jlen[i] *= -1 if dir[i] == '<'
end

cur_pos = 0
while 0 <= cur_pos && cur_pos < n
  if used[cur_pos]
    puts 'INFINITE'
    exit
  end
  used[cur_pos] = true
  cur_pos+=jlen[cur_pos]
end

#puts jlen
puts 'FINITE'

l = gets.to_i
dirs = gets.to_s
nums = gets.split(' ').map { |i| i.to_i }
ex = false
next_pos = 0
nums.each_with_index { |n, i|
  next_pos = dirs[i] == '>' ? next_pos + n : next_pos - n
  if next_pos > l or next_pos < 0
    ex = true
    break
  end
}
puts ex ? 'FINITE' : 'INFINITE'

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

FIN = 'FINITE'
INF = 'INFINITE'

n = gi
j = gs.each_char.to_a
d = gis

jp = j.zip(d).map{|y, x| y == "<" ? -x : x}

f = [false] * jp.size

i = 0

loop {
    if f[i]
        puts INF
        exit
    end
    f[i] = true
    i += jp[i]
    if i < 0 || i >= n - 1
        puts FIN
        exit
    end
}

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

FIN = 'FINITE'
INF = 'INFINITE'

n = gi
j = gs.each_char.to_a
d = gis

a = j.zip(d).reduce(0) {|r,k|
    y, x = k
    y == "<" ? r - x : r + x
}

if a < 0
    puts FIN
else
    puts INF
end

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

FIN = 'FINITE'
INF = 'INFINITE'

n = gi
j = gs.each_char.to_a
d = gis

a = j.zip(d).reduce(0) {|r,k|
    if r < 0
        puts FIN
        exit
    end
    y, x = k
    y == "<" ? r - x : r + x
}

if a < 0
    puts FIN
else
    puts INF
end

n = gets.to_i
s = gets
values = gets.split.map{|x| x.to_i}
vis = Array.new(n , false)

i = 0
flag = false

while (vis[i] == false)

	vis[i] = true

	if(s[i] == '>')
		i += values[i]
	else
		i -= values[i]

	end

	if(i < 0 || i >= s.length)
		flag = true
		break
	end
end

puts "FINITE" if flag == true
puts "INFINITE" if flag == false

n = gets.to_i
s = gets
values = gets.split.map{|x| x.to_i}
vis = Array.new(n , false)

i = 0
flag = false

while (vis[i] == false)

	vis[i] = true

	if(s[i] == '>')
		i += values[i]
	else
		i -= values[i]

	end

	if(i < 0 || i >= s.length)
		flag = true
		break
	end
end

p "FINITE" if flag == true
p "INFINITE" if flag == false


Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things:  Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one);  Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves:  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$.  You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$.  You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$.  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$.  You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the lower bound on the sum of the array.

For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    ans = n ** (1/2.0)
    min = ans.floor
    max = ans.ceil
    count = 0

    if n == min ** 2
        count = (min - 1) + (min - 1)
    else
        sa = n - min ** 2
        count = min - 1 + (min - 1 ) + 1 + (sa / max)
    end
    puts count
end


There are $$$n$$$ candies put from left to right on a table. The candies are numbered from left to right. The $$$i$$$-th candy has weight $$$w_i$$$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa).They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the number of candies on the table. The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \leq w_i \leq 10^4$$$) — the weights of candies from left to right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print a single integer — the maximum number of candies Alice and Bob can eat in total while satisfying the condition.

NoteFor the first test case, Alice will eat one candy from the left and Bob will eat one candy from the right. There is no better way for them to eat the same total amount of weight. The answer is $$$2$$$ because they eat two candies in total.For the second test case, Alice will eat the first three candies from the left (with total weight $$$7$$$) and Bob will eat the first three candies from the right (with total weight $$$7$$$). They cannot eat more candies since all the candies have been eaten, so the answer is $$$6$$$ (because they eat six candies in total).For the third test case, there is no way Alice and Bob will eat the same non-zero weight so the answer is $$$0$$$.For the fourth test case, Alice will eat candies with weights $$$[7, 3, 20]$$$ and Bob will eat candies with weights $$$[10, 8, 11, 1]$$$, they each eat $$$30$$$ weight. There is no better partition so the answer is $$$7$$$.

def eating_cadies(arr, n)
  i = 0
  j = n - 1
  alice = arr[0]
  bob = arr[j]
  count = 0
  while i < j
    if alice == bob
      count = [count, i+1+n-j].max
    end
    if alice <= bob
      i+=1
      alice+=arr[i]
    elsif bob < alice
      j-=1
      bob+=arr[j]
    end

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

inputs.each do |input|
  puts eating_cadies(input[0], input[1])
end

gets.to_i.times do
  gets()
  xs = gets.split.map(&:to_i)
  h = {}
  sum = 0
  xs.each_with_index do |x, i|
    sum += x
    h[sum] = i + 1
  end

  ans = 0
  sum = 0
  xs.reverse.each_with_index do |x, i|
    sum += x
    if h.include?(sum)
      j = xs.size() - h[sum] + 1
      if j > i + 1
        ans = [ans, h[sum] + i + 1].max
      end
    end
  end

  p ans
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  l, r = 0, xs.size - 1
  sl, sr, max, ate = 0, 0, 0, 0
  while l <= r
    if sl < sr || (sl == sr && xs[l] < xs[r])
      sl += xs[l]
      l += 1
    else
      sr += xs[r]
      r -= 1
    end
    ate += 1
    max = ate if sl == sr
  end
  p max
end

def eating_cadies(arr, n)
  i = 0
  j = n - 1
  alice = arr[0]
  bob = arr[j]
  count = 0
  while i < j
    if alice <= bob
      i+=1
      alice+=arr[i]
    elsif bob < alice
      j-=1
      bob+=arr[j]
    end
    if alice == bob
      count = [count, i+1+n-j].max
    end
  end
   count
end
t = gets.to_i
inputs = []
(0..t-1).each do |i|
  n = gets.to_i
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)
  inputs.push([arr, n])
end

inputs.each do |input|
  puts eating_cadies(input[0], input[1])
end


When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i ≤ j).Then the simple prettiness of s is defined by the formula:The prettiness of s equals Find the prettiness of the given song title.We assume that the vowels are I, E, A, O, U, Y.

The input contains a single string s (1 ≤ |s| ≤ 5·105) — the title of the song.

Print the prettiness of the song with the absolute or relative error of at most 10 - 6.

NoteIn the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.

d=gets
n=d.size-1
sum,ans,now=[0],0,0
n.times{|i|sum[i+1]=sum[i]+1.0/(i+1)}
(0...n).each do |i|
  now+=sum[-i-1]-sum[i]
  ans+=now if 'IEAOUY'[d[i]]
end
p ans

v=['I','E','A','O','U','Y']
d=['Q']+gets.split(//)
d.pop
n=d.size-1
sum,ans,now=[0.0],0.0,0.0
n.times{|i|sum[i+1]=sum[i]+1.0/(i+1)}
(1..n/2).each do |i|
  now+=sum[-i]-sum[i-1]
  ans+=now if v.include?d[i]
  ans+=now if v.include?d[-i]
end
now+=sum[n/2+1]-sum[n/2]
ans+=now if n.odd?&&v.include?(d[n/2+1])
p ans

gets
sum,a,now,n=[0],0,0,$_.size-1
n.times{|i|sum[i+1]=sum[i]+1.0/(i+1)}
(0...n).each do |i|
  now+=sum[-i-1]-sum[i]
  a+=now if 'IEAOUY'[$_[i]]
end
p a

d=gets.split(//)
d.pop
n=d.size
sum,ans,now=[0],0,0
n.times{|i|sum[i+1]=sum[i]+1.0/(i+1)}
(0...n).each do |i|
  now+=sum[-i-1]-sum[i]
  ans+=now if 'IEAOUY'[d[i]]
end
p ans


To stay woke and attentive during classes, Karen needs some coffee!  Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.Karen thinks that a temperature is admissible if at least k recipes recommend it.Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?

The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively. The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 ≤ li ≤ ri ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive. The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.

For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.

NoteIn the first test case, Karen knows 3 recipes.  The first one recommends brewing the coffee between 91 and 94 degrees, inclusive.  The second one recommends brewing the coffee between 92 and 97 degrees, inclusive.  The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it.She asks 4 questions.In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.In the second test case, Karen knows 2 recipes.  The first one, "wikiHow to make Cold Brew Coffee", recommends brewing the coffee at exactly 1 degree.  The second one, "What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it.In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.

N, K, Q = gets.split.map(&:to_i)
ims = Array.new(200000 + 1 + 1, 0)
N.times {
  a, b = gets.split.map(&:to_i)
  ims[a] += 1
  ims[b + 1] -= 1
}
200000.times { |i|
  ims[i + 1] += ims[i]
}
pre = Array.new(200000 + 1 + 1, 0)
200000.times { |i|
  pre[i + 1] = pre[i] + (ims[i + 1] >= K ? 1 : 0)
}
Q.times {
  a, b = gets.split.map(&:to_i)
  puts pre[b] - pre[a - 1]
}

N, K, Q = $stdin.readline.split.map(&:to_i)
ims = Array.new(200000 + 1 + 1, 0)
N.times {
  a, b = $stdin.readline.split.map(&:to_i)
  ims[a] += 1
  ims[b + 1] -= 1
}
200000.times { |i|
  ims[i + 1] += ims[i]
}
pre = Array.new(200000 + 1 + 1, 0)
200000.times { |i|
  pre[i + 1] = pre[i] + (ims[i + 1] >= K ? 1 : 0)
}
Q.times {
  a, b = $stdin.readline.split.map(&:to_i)
  puts pre[b] - pre[a - 1]
}

N, K, Q = $stdin.gets.split.map(&:to_i)
ims = Array.new(200000 + 1 + 1, 0)
N.times {
  a, b = $stdin.gets.split.map(&:to_i)
  ims[a] += 1
  ims[b + 1] -= 1
}
200000.times { |i|
  ims[i + 1] += ims[i]
}
pre = Array.new(200000 + 1 + 1, 0)
200000.times { |i|
  pre[i + 1] = pre[i] + (ims[i + 1] >= K ? 1 : 0)
}
Q.times {
  a, b = $stdin.gets.split.map(&:to_i)
  puts pre[b] - pre[a - 1]
}


Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

The first line contains a single integer n (1 ≤ n ≤ 105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0 ≤ hi ≤ 23; 0 ≤ mi ≤ 59), representing the time when the i-th person comes into the cafe.  Note that the time is given in the chronological order. All time is given within one 24-hour period.

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash.

n = gets.to_i
b = []
x,y = 1,0
n.times do |i|
	 a = gets.split.map(&:to_i)
	 if a == b
	 	y += 1
	 	x = [x,y].max
	 else
	 	y = 1
	 end
	 b = a
end
p x

i = gets.to_i; x = Hash.new(0);
i.times { x[gets.chomp] += 1 }
puts x.values.max

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ph, pm = -1, -1
cons = 0
max_cons = 0
n.times {
    h, m = gets.split.map(&:to_i)
    if h != ph || m != pm
        if max_cons < cons
            max_cons = cons
        end
        cons = 0
        ph, pm = h, m
    end

    cons += 1

    if max_cons < cons
        max_cons = cons
    end
}
puts max_cons

h = Hash.new(0)
gets.to_i.times {
    h[gets.chomp] += 1
}

p h.values.max

n = gets.chomp.to_i
cashiers = []
for i in (0..n-1)
	cashiers[i] = gets.chomp
end

cashes = 1
free = 0
for i in (0..cashiers.size - 2)
	if cashiers[i] == cashiers[i+1] && free <= 1
		cashes += 1
	else
		if cashiers[i] == cashiers[i+1]
			free -= 1
		else
			free = cashes
		end
	end
end

print cashes

def max_cash(arrival_times)
    max = 0
    counter = 0
    prev_value = arrival_times[0]

    arrival_times.each do |arrival_time|
        if arrival_time == prev_value
            counter += 1
        else
            counter = 1
        end
        prev_value = arrival_time
        max = [max, counter].max
    end

    max
end

n = gets.chomp.to_i
clientes_arrival_time = []
n.times do
    clientes_arrival_time << gets.chomp.gsub(" ", ":")
end

puts max_cash(clientes_arrival_time)

def max_cash(arrival_times)
    arrival_time_counter = Hash.new { |k, v| k[v] = 0 }

    arrival_times.each do |arrival_time|
        arrival_time_counter[arrival_time] += 1
    end

    arrival_time_counter.values.max
end

n = gets.chomp.to_i
clientes_arrival_time = []
n.times do
    clientes_arrival_time << gets.chomp.gsub(" ", ":")
end

puts max_cash(clientes_arrival_time)

n = gets.to_i
a = Hash.new(0)
n.times do
  a[gets.chomp] += 1
end
puts a.values.max

n = gets.to_i
a = Array.new(24){Array.new(60, 0)}
n.times do
  h, m = gets.split.map(&:to_i)
  a[h][m] += 1
end
aa = []
24.times do |i|
  aa[i] = a[i].max
end
p aa.max

n = gets.chomp.to_i
d = {}
n.times do
  h, m = gets.chomp.split(" ").map(&:to_i)
  d[[h, m]] = d.fetch([h, m], 0) + 1
end
puts d.values.max

n = gets.to_i
c = {}
n.times do
    h, m = gets.split.map{|x| x.to_i}
    c[[h, m]] = 0 unless c[[h, m]]
    c[[h, m]] += 1
end
puts c.max{|a, b| a[1] <=> b[1]}[1]

n = gets.to_i

time = Hash.new(0)
max = 0
n.times do |_|
  h, m = gets.split(" ").map(&:to_i)
  max = [max, time[m + h*60] += 1].max
end

p max

n = gets.to_i

time = Hash.new(0)
n.times do |_|
  h, m = gets.split(" ").map(&:to_i)
  time[h*60 + m] += 1
end

p time.max { |a, b| a[1] <=>  b[1]}[1]

n = gets.to_i

time = Hash.new(0)
n.times do |_|
  h, m = gets.split(" ").map(&:to_i)
  time[h*60 + m] += 1
end

p time.values.max

n = gets.to_i

time = Hash.new(0)
n.times do |_|
  h, m = gets.split(" ").map(&:to_i)
  time[h*60 + m] += 1
end

p time.max_by { |k, v| v}[1]

n = gets.to_i

time = Hash.new(0)
max = 0
n.times do |_|
  h, m = gets.split(" ").map(&:to_i)
  m += h*60
  time[m] += 1
  max = [max, time[m]].max
end

p max

n = gets.to_i
pr = [-1, -1]
tmp, max = 0, 1
n.times do
  ar = gets.split(' ').map(&:to_i)
  ar == pr ? tmp+=1 : tmp = 1
  max = tmp if tmp > max
  pr = ar
end
puts max

a=Array.new(24*60+1,0)

#print a
n=gets.chomp.to_i
i=0
for i in (0...n)
b=gets.chomp.split(" ")
a[(b[0].to_i*60+b[1].to_i)]+=1
end
puts a.max

a=Hash.new(0)

#print a
n=gets.chomp.to_i
i=0
for i in (0...n)
b=gets.chomp.split(" ")
a[(b[0].to_i*60+b[1].to_i)]+=1
end
puts a.values.max

n = gets.to_i

t = {}
n.times do |i|
    s = gets.chomp.sub(" ", ":")
    if t[s] then
        t[s] += 1
    else
        t[s] = 1
    end
end

t = t.sort{|a,b| a[1]<=>b[1]}

p t[-1][1]

h = Hash.new(0)
gets.to_i.times{
  h[gets] += 1
}
p h.values.max

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

aa = bb = -1; cnt = res = 1; RD[].times{
	a, b = I[]
	if a == aa && b == bb
		cnt += 1; res = cnt if (cnt > res)
	else
		cnt = 1; aa,  bb = a, b
	end
}

p res

n = gets.to_i
hLast, mLast = -1, -1
max = 1
count = 1
n.times do
  h, m = gets.split(" ").map(&:to_i)
  if hLast == h && mLast == m
    count += 1
  else
    count = 1
  end
  max = count if count > max
  hLast, mLast = h, m
end

puts max

n = gets.chomp.to_i

hash = {}
n.times do
  v = gets.chomp
  if hash.has_key? v
    hash[v] += 1
  else
    hash[v] = 1
  end
end

puts hash.values.max

n = gets.to_i
cus = Array.new(24)
for i in 0...24
  cus[i] = Array.new(60, 0)
end
n.times do
  a, b = gets.split.map(&:to_i)
  cus[a][b] += 1
end
m = Array.new
for i in 0...24
  m << cus[i].max
end
print m.max

times = []
people = gets.chomp.to_i
people.times { time = gets
  times.push(time) }

b = Hash.new(0)
times.each do |element|
  b[element] += 1
end

p b.values.max

hash = Array.new(24*60) {0}
f = Proc.new{ |a,b| a * 60 + b }
gets.to_i.times {
  hash[f.call gets.split.map(&:to_i)] += 1
}
puts hash.max

a = Hash.new(0)
gets.to_i.times { a[gets.strip] += 1 }
puts a.values.max

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

h = {}

a.each_with_index do |t, i|
  h[t] = (h[t].nil? ? 1 : h[t]+1)
end

puts h.values.max

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

c   = 0
fox = []
cox.sort!
for i in 0..n-1
  if cox[i] == cox[i+1]
    c+=1
  else
    fox.push(c)
    c = 0
  end
end

puts fox.max + 1

n = $stdin.gets.to_i
r = []
n.times {r << $stdin.readline.chop}

class Array # use self.partition

    def complect_and_count
        self.dup.complect_and_count!
    end

    def complect_and_count!
        a = self.shift
        h = {sym: a, count: 1}
        result, k = [h], 1
        while self.size>0
            b = self.shift
            if a != b
                h[:count] = k
                h =  {sym: b, count: 1}
                result << h
                k = 0
            end
            a = b
            k += 1
        end
        h[:count]=k
        result
    end

end

t = r.complect_and_count
m = t.max_by {|x| x[:count]}

puts m[:count]

arr = []
gets.to_i.times do
  arr << gets.chomp
end
hash = Hash.new(0)
arr.each { |v| hash[v] += 1 }
puts hash.values.max

t = []
max_t = 1
gets.to_i.times do |i|
  in_time = gets.chomp.split.map(&:to_i)
  tt = in_time[0]*60 + in_time[1]
  if t[tt].nil?
    t[tt] = 1
  else
    t[tt] += 1
  end
  max_t = t[tt] if t[tt] > max_t
end
puts max_t

n=gets.to_i
n-=1
s=gets.chomp
ans=1
c=1
n.times{
	s2=gets.chomp
	if s==s2 then
		c=c+1
	else
		c=1
		s=s2
	end
	ans=[ans,c].max
}
puts ans

i = gets.to_i; x = Hash.new(0);
i.times { x[gets.chomp] += 1 }
puts x.max[1]

customers = gets.chomp.to_i
time = []
for i in (0..customers-1)
	t = gets.chomp
	time[i] = t.split
	time[i] = (time[i][0].to_i * 60) + time[i][1].to_i
end

cashiers = 1
for i in (0..customers-2)
	if time[i] == time[i+1] || (time[i]).abs - (time[i+1]).abs == 1
		cashiers += 1
	end
end

print cashiers

n = gets.chomp.to_i
cashiers = []
for i in (0..n-1)
	cashiers[i] = gets.chomp
end

cashes = 0
available = 0
for i in (0..n-2)
	if cashiers[i] == cashiers[i+1]
		if cashes == 0 && available == 0
			cashes += 2
		elsif available == 0
			cashes += 1
		end
	else
		available = cashes
	end
end
if cashes == 0
	print 1
else
	print cashes
end

n = gets.to_i
a = Array.new(24, Array.new(60, 0))
n.times do
  h, m = gets.split.map(&:to_i)
  a[h][m] += 1
end
aa = []
24.times do |i|
  aa[i] = a[i].max
end
p aa.max

n = gets.to_i
a = Array.new(24, Array.new(60, 0))
n.times do
  h, m = gets.split.map(&:to_i)
  a[h][m] += 1
end
p a.max.max

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

k = 1

puts k + (n - cox.uniq.size)

arr = []
gets.to_i.times do
  arr << gets.chomp
end
puts 1 + (arr.size - arr.uniq.size)

n = gets.to_i
b = []
x,y = 0,0
n.times do |i|
	 a = gets.split.map(&:to_i)
	 if a == b
	 	y += 1
	 	x = [x,y].max
	 else
	 	y = 1
	 end
	 b = a
end
p x


You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $$$p$$$ units and your follower — at most $$$f$$$ units.In the blacksmith shop, you found $$$cnt_s$$$ swords and $$$cnt_w$$$ war axes. Each sword weights $$$s$$$ units and each war axe — $$$w$$$ units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$p$$$ and $$$f$$$ ($$$1 \le p, f \le 10^9$$$) — yours and your follower's capacities. The second line of each test case contains two integers $$$cnt_s$$$ and $$$cnt_w$$$ ($$$1 \le cnt_s, cnt_w \le 2 \cdot 10^5$$$) — the number of swords and war axes in the shop. The third line of each test case contains two integers $$$s$$$ and $$$w$$$ ($$$1 \le s, w \le 10^9$$$) — the weights of each sword and each war axe. It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.

NoteIn the first test case:   you should take $$$3$$$ swords and $$$3$$$ war axes: $$$3 \cdot 5 + 3 \cdot 6 = 33 \le 33$$$  and your follower — $$$3$$$ swords and $$$2$$$ war axes: $$$3 \cdot 5 + 2 \cdot 6 = 27 \le 27$$$.  $$$3 + 3 + 3 + 2 = 11$$$ weapons in total.In the second test case, you can take all available weapons even without your follower's help, since $$$5 \cdot 10 + 5 \cdot 10 \le 100$$$.In the third test case, you can't take anything, but your follower can take $$$3$$$ war axes: $$$3 \cdot 5 \le 19$$$.

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  max = 0
  (cnt1+1).times do |i|
    next if i*s>p
    num_p_s = i
    rest_p = p - i*s
    rest_cnt_s = cnt1-i
    num_p_w = [rest_p/w, cnt2].min
    rest_cnt_w = cnt2 - num_p_w
    num_f_s = 0
    num_f_w = 0
    if s > w
      num_f_w = [f/w, rest_cnt_w].min
      rest_f = f - num_f_w*w
      num_f_s = [rest_f/s, rest_cnt_s].min
    else
      num_f_s = [f/s, rest_cnt_s].min
      rest_f = f - num_f_s*s
      num_f_w = [rest_f/w, rest_cnt_w].min
    end
    max = [num_p_s + num_p_w + num_f_s + num_f_w, max].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  if p < f
    p,f = f,p
  end
  if s < w
    s,w = w,s
    cnt1,cnt2 = cnt2,cnt1
  end
  num2 = f / w
  if num2 > cnt2
    num2 = cnt2
  end
  cnt2 -= num2
  f -= num2 * w
  num1 = 0
  if f >= s
    num1 = f / s
    if num1 > cnt1
      num1 = cnt1
    end
    cnt1 -= num1
  end
  num3 = 0
  num4 = 0
  if cnt2 > 0
    num4 = p / w
    if num4 > cnt2
      num4 = cnt2
    end
    cnt2 -= num4
    p -= num4 * w
  end
  if p >= s
    num3 = p / s
    if num3 > cnt1
      num3 = cnt1
    end
    cnt1 -= num3
    p -= num3 * s
  end
  max = num1+num2+num3+num4
  puts "#{num1} #{num2} #{num3} #{num4} #{cnt1} #{cnt2} #{p} #{f}"
  while num2 > 0
    num2 -= 1
    f += w
    cnt2 += 1
    if f >= s && cnt1 > 0
      num1 += 1
      cnt1 -= 1
      f -= s
    end
    if num3 > 0 && cnt2 > 0
      num3 -= 1
      cnt1 += 1
      num4 += 1
      cnt2 -= 1
      p = p + s - w
    end
    if p >= w  && cnt1 > 0
      nu = p / w
      if nu > cnt1
        nu = cnt1
      end
      num4 += nu
      cnt1 -= nu
      p -= nu * w
    end
    max = [max,num1+num2+num3+num4].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  max = 0
  cnt1.times do |i|
    next if i*s>p
    num_p_s = i
    rest_p = p - i*s
    rest_cnt_s = cnt1-i
    num_p_w = [rest_p/w, cnt2].min
    rest_cnt_w = cnt2 - num_p_w
    num_f_s = 0
    num_f_w = 0
    if s > w
      num_f_w = [f/w, rest_cnt_w].min
      rest_f = f - num_f_w*w
      num_f_s = [rest_f/s, rest_cnt_s].min
    else
      num_f_s = [f/s, rest_cnt_s].min
      rest_f = f - num_f_s*s
      num_f_w = [rest_f/w, rest_cnt_w].min
    end
    max = [num_p_s + num_p_w + num_f_s + num_f_w, max].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  if p < f
    p,f = f,p
  end
  if s < w
    s,w = w,s
    cnt1,cnt2 = cnt2,cnt1
  end
  num2 = f / w
  if num2 > cnt2
    num2 = cnt2
  end
  cnt2 -= num2
  f -= num2 * w
  num1 = 0
  if f >= s
    num1 = f / s
    if num1 > cnt1
      num1 = cnt1
    end
    cnt1 -= num1
  end
  num3 = 0
  num4 = 0
  if cnt2 > 0
    num4 = p / w
    if num4 > cnt2
      num4 = cnt2
    end
    cnt2 -= num4
    p -= num4 * w
  end
  if p >= s
    num3 = p / s
    if num3 > cnt1
      num3 = cnt1
    end
    cnt1 -= num3
    p -= num3 * s
  end
  max = num1+num2+num3+num4
  puts "#{num1},#{num2},#{num3},#{num4},#{cnt1},#{cnt2},#{p},#{f}"
  while num2 > 0
    num2 -= 1
    f += w
    cnt2 += 1
    if f >= s && cnt1 > 0
      num1 += 1
      cnt1 -= 1
      f -= s
    end
    if num3 > 0 && cnt2 > 0
      num3 -= 1
      cnt1 += 1
      num4 += 1
      cnt2 -= 1
      p = p + s - w
    end
    if p >= s  && cnt1 > 0
      nu = p / s
      if nu > cnt1
        nu = cnt1
      end
      num4 += nu
      cnt2 -= nu
      p -= nu * w
    end
    max = [max,num1+num2+num3+num4].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  if p < f
    p,f = f,p
  end
  if s < w
    s,w = w,s
    cnt1,cnt2 = cnt2,cnt1
  end
  num2 = f / w
  if num2 > cnt2
    num2 = cnt2
  end
  cnt2 -= num2
  f -= num2 * w
  num1 = 0
  if f >= s
    num1 = f / s
    if num1 > cnt1
      num1 = cnt1
    end
    cnt1 -= num1
  end
  num3 = 0
  num4 = 0
  if cnt2 > 0
    num4 = p / w
    if num4 > cnt2
      num4 = cnt2
    end
    cnt2 -= num4
    p -= num4 * w
  end
  if p >= s
    num3 = p / s
    if num3 > cnt1
      num3 = cnt1
    end
    cnt1 -= num3
    p -= num3 * s
  end
  max = num1+num2+num3+num4
  while num2 > 0
    num2 -= 1
    f += w
    cnt2 += 1
    if f >= s && cnt1 > 0
      num1 += 1
      cnt1 -= 1
      f -= s
    end
    if num3 > 0 && cnt2 > 0
      num3 -= 1
      cnt1 += 1
      num4 += 1
      cnt2 -= 1
      p = p + s - w
    end
    if p >= s  && cnt1 > 0
      nu = p / s
      if nu > cnt1
        nu = cnt1
      end
      num4 += nu
      cnt2 -= nu
      p -= nu * w
    end
    max = [max,num1+num2+num3+num4].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  if p < f
    p,f = f,p
  end
  if s < w
    s,w = w,s
    cnt1,cnt2 = cnt2,cnt1
  end
  num2 = f / w
  if num2 > cnt2
    num2 = cnt2
  end
  cnt2 -= num2
  f -= num2 * w
  num1 = 0
  if f >= s
    num1 = f / s
    if num1 > cnt1
      num1 = cnt1
    end
    cnt1 -= num1
  end
  num3 = 0
  num4 = 0
  if cnt2 > 0
    num4 = p / w
    if num4 > cnt2
      num4 = cnt2
    end
    cnt2 -= num4
    p -= num4 * w
  end
  if p >= s
    num3 = p / s
    if num3 > cnt1
      num3 = cnt1
    end
    cnt1 -= num3
    p -= num3 * s
  end
  max = num1+num2+num3+num4
  while num2 > 0
    num2 -= 1
    f += w
    cnt2 += 1
    if f >= s && cnt1 > 0
      num1 += 1
      cnt1 -= 1
      f -= s
    end
    if num3 > 0 && cnt2 > 0
      num3 -= 1
      cnt1 += 1
      num4 += 1
      cnt2 -= 1
      p = p + s - w
    end
    if p >= w  && cnt1 > 0
      nu = p / w
      if nu > cnt1
        nu = cnt1
      end
      num4 += nu
      cnt1 -= nu
      p -= nu * w
    end
    max = [max,num1+num2+num3+num4].max
  end
  ans << max
end
ans.each do |x|
  puts x
end

t = gets.to_i
ans = []
t.times do
  p,f = gets.chomp.split(" ").map(&:to_i)
  cnt1,cnt2 = gets.chomp.split(" ").map(&:to_i)
  s,w = gets.chomp.split(" ").map(&:to_i)
  if p < f
    p,f = f,p
  end
  if s < w
    s,w = w,s
    cnt1,cnt2 = cnt2,cnt1
  end
  num2 = f / w
  if num2 > cnt2
    num2 = cnt2
  end
  cnt2 -= num2
  f -= num2 * w
  num1 = 0
  if f >= s
    num1 = f / s
    if num1 > cnt1
      num1 = cnt1
    end
    cnt1 -= num1
    f -= num1 * s
  end
  num3 = 0
  num4 = 0
  if cnt2 > 0
    num4 = p / w
    if num4 > cnt2
      num4 = cnt2
    end
    cnt2 -= num4
    p -= num4 * w
  end
  if p >= s
    num3 = p / s
    if num3 > cnt1
      num3 = cnt1
    end
    cnt1 -= num3
    p -= num3 * s
  end
  max = num1+num2+num3+num4
  while num2 > 0
    num2 -= 1
    f += w
    cnt2 += 1
    if num3 > 0 && cnt2 > 0
      num3 -= 1
      cnt1 += 1
      num4 += 1
      cnt2 -= 1
      p = p + s - w
    end
    if f >= s && cnt1 > 0
      num1 += 1
      cnt1 -= 1
      f -= s
    end
    if p >= s  && cnt1 > 0
      nu = p / s
      if nu > cnt1
        nu = cnt1
      end
      num3 += nu
      cnt1 -= nu
      p -= nu * s
    end
    max = [max,num1+num2+num3+num4].max
  end
  ans << max
end
ans.each do |x|
  puts x
end


Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., wi. Each thrown box flies vertically down until at least one of the two following events happen:  the bottom of the box touches the top of a stair;  the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi + 1.You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.

The first line contains integer n (1 ≤ n ≤ 105) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a1, a2, ..., an (1 ≤ ai ≤ 109; ai ≤ ai + 1). The next line contains integer m (1 ≤ m ≤ 105) — the number of boxes. Each of the following m lines contains a pair of integers wi, hi (1 ≤ wi ≤ n; 1 ≤ hi ≤ 109) — the size of the i-th thrown box. The numbers in the lines are separated by spaces.

Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteThe first sample are shown on the picture.

n=gets.to_i
a=gets.split.map(&:to_i)
gets.to_i.times do
    w,h=gets.split.map(&:to_i)
    t=[a[0], a[w-1]].max
    puts t
    a[0]=t+h
end

n = gets.to_i #kol stypenei
a = gets.split(' ').collect!{|i| i.to_i} #visota stypenei
m = gets.to_i #kol korobok

w = []
h = []
m.times do
	t=gets.split(' ')
	w << t[0].to_i
	h << t[1].to_i
end

x = []

# m.times do |i|
# 	wid = w[i]-1
# 	hei = h[i]
# 	x << a[wid]
# 	newhei = a[wid]+hei
# 	n.times do |j|
# 		if newhei > a[j]
# 			a[j] = newhei
# 		else
# 			break
# 		end
# 	end
# end
newhei = 0
m.times do |i|
	wid = w[i]-1
	if a[wid] > newhei
		x << a[wid]
		newhei = a[wid]+h[i]
	else
		x << newhei
		newhei += h[i]
	end
end

puts x

n = gets.to_i #kol stypenei
a = gets.split(' ').collect!{|i| i.to_i} #visota stypenei
m = gets.to_i #kol korobok

w = []
h = []
m.times do
	t=gets.split(' ')
	w << t[0].to_i
	h << t[1].to_i
end

x = []

m.times do |i|
	wid = w[i]-1
	hei = h[i]
	x << a[wid]
	newhei = a[wid]+hei
	(0..(wid)).each do |j|
		a[j] = newhei
	end
end

puts x


The only difference between the two versions is that in this version $$$n \leq 1000$$$ and the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.A terminal is a row of $$$n$$$ equal segments numbered $$$1$$$ to $$$n$$$ in order. There are two terminals, one above the other. You are given an array $$$a$$$ of length $$$n$$$. For all $$$i = 1, 2, \dots, n$$$, there should be a straight wire from some point on segment $$$i$$$ of the top terminal to some point on segment $$$a_i$$$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $$$n=7$$$ and $$$a=[4,1,4,6,7,7,5]$$$.  A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.

For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.

NoteThe first test case is shown in the second picture in the statement.In the second test case, the only wiring possible has the two wires cross, so the answer is $$$1$$$.In the third test case, the only wiring possible has one wire, so the answer is $$$0$$$.

def merge_sort(l, r)
  return if r <= l + 1
  m = (l + r) / 2

  merge_sort(l, m)
  merge_sort(m, r)

  i = l
  j = m
  o = l
  while i < m && j < r
    if $xs[j] <= $xs[i]
      $inversions += m - i
      $tmp[o] = $xs[j]
      j += 1
    else
      $tmp[o] = $xs[i]
      i += 1
    end
    o += 1
  end

  while i < m
    $tmp[o] = $xs[i]
    i += 1
    o += 1
  end

  while j < r
    $tmp[o] = $xs[j]
    j += 1
    o += 1
  end

  $xs[l...r] = $tmp[l...r]
end

def inversions(xs)
  $xs = xs
  $tmp = Array.new(xs.size)
  $inversions = 0
  merge_sort(0, xs.size)
  $inversions
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  p inversions(xs)
end

main = -> {
  t = int
  t.times do
      n = int
      a = int1s
      ans = 0
      n.times do |i|
          ans += (0 ... i).count { |j| a[j] >= a[i] }
      end
      puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

class Segtree
  def initialize(size, id, fill = id, &op)
    if size.is_a? Array
      @n = 1 << (size.size - 1).bit_length
      @a = [fill] * (2 * @n)
      @a[@n, @n] = size
      (@n - 1).downto(1) do |i|
        @a[i] = op[@a[i * 2], @a[i * 2 + 1]]
      end
    else
      @n = 1 << (size - 1).bit_length
      @a = [fill] * (2 * @n)
    end
    @a[0], @op = id, op
  end
  def [](i) @a[i + @n] end
  def []=(i, x)
    @a[i += @n] = x
    @a[i] = @op[@a[i * 2], @a[i * 2 + 1]] while (i >>= 1) > 0
  end
  def prod(l, r)
    return @a[0] if l >= r
    x = prod(l + 1 >> 1, r >> 1)
    x = @op[@a[@n + l], x] if l & 1 == 1
    x = @op[x, @a[@n + r - 1]] if r & 1 == 1
    x
  end
end

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.

The first line contains string s of length n.  The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.

Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.

NoteIn the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.

a, b = gets, gets
n, c = a.length, 0
(0...n).each do |i|
	if a[i] != b[i]
		c += 1
	end
end

if c & 1 != 0
	puts "impossible"
else
	p, i = 0, 0
	while i < n do
		if p >= c/2
			break
		end
		if a[i] != b[i]
			print b[i]
			p += 1
		else
			print a[i]
		end
		i += 1
	end
	puts a[i..-1]
end

a, b = gets, gets
n, c = a.length, 0
(0...n).each do |i|
	if a[i] != b[i]
		c += 1
	end
end

if c & 1 != 0
	puts "impossible"
else
	s, p, i = '', 0, 0
	while i < n do
		if p >= c/2
			break
		end
		if a[i] != b[i]
			s << b[i]
			p += 1
		else
			s << a[i]
		end
		i += 1
	end
	s << a[i..-1]
	puts s
end

s = gets
t = gets
z = s.split('').zip(t.split(''))
dist = 0
z.each do |si, ti|
    dist += 1 if si != ti
end
if dist.odd?
    puts 'impossible'
else
    dist /= 2
    z.each do |si, ti|
        if si == ti
            print si
        else
            if dist > 0
                dist -= 1
                print si
            else
                print ti
            end
        end
    end
    puts
end

# http://codeforces.com/contest/545/problem/B
def hd(a, b)
  (0...a.length).map do |idx|
    a[idx] == b[idx] ? 0 : 1
  end.inject(0, :+)
end

def modify(a, b, n)
  (0...a.length).map do |idx|
    if a[idx] == b[idx]
      a[idx]
    else
      if n > 0
        n -= 1
        a[idx]
      else
        b[idx]
      end
    end
  end.join
end

s = gets.chomp.chars
t = gets.chomp.chars
d = hd(s, t)

if d.even?
  puts modify(s, t, d / 2)
else
  puts 'impossible'
end

s=gets.chomp
t=gets.chomp

c1=0
s.size.times{|i|
	c1+=1 if s[i]!=t[i]
}

if c1%2==1 then
	puts "impossible"
else
	ans=""
	f=true
	s.size.times{|i|
		if s[i]==t[i] then
			ans<<s[i]
		else
			if f then
				ans<<s[i]
			else
				ans<<t[i]
			end
			f=!f
		end
	}
	puts ans
end

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

# b.rb

def main()
    s = gets.chomp
    t = gets.chomp
    v = 0
    s.size.times do |i|
        if s[i] != t[i] then
            s[i] = [s[i],t[i]][v % 2]
            v += 1
        end
    end
    if (v % 2) == 0 then
        puts s
    else
        puts "impossible"
    end
end

if __FILE__ == $0 then
    main()
end

A = gets.strip.chars
B = gets.strip.chars

diff = 0
answer = []
A.zip(B).map do |a, b|
  if a == b
    answer.push a
  else
    if diff >= 0
      answer.push a
      diff -= 1
    else
      answer.push b
      diff += 1
    end
  end
end

if diff != 0
  puts "impossible"
else
  puts answer.join
end

# http://codeforces.com/contest/545/problem/B
def hd(a, b)
  (0...a.length).map do |idx|
    a[idx] == b[idx] ? 0 : 1
  end.inject(0, :+)
end

def pad(chars)
  (0...chars.length).to_a.reverse.each do |idx|
    if chars[idx] == '0'
      chars[idx] = '1'
      break
    end
  end

  chars.join
end

s = gets.chomp
t = gets.chomp
s, t = [s, t].sort
d = hd(s.chars, t.chars)

if d.even?
  puts pad(s.chars)
else
  puts 'impossible'
end

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

# b.rb

def main()
    s = gets.chomp
    t = gets.chomp
    v = 0
    s.size.times do |i|
        if s[i] != t[i] then
            s[i] = "10"[v % 2]
            v += 1
        end
    end
    if (v % 2) == 0 then
        puts s
    else
        puts "impossible"
    end
end

if __FILE__ == $0 then
    main()
end

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

# b.rb

def main()
    s = gets
    t = gets
    v = 0
    s.size.times do |i|
        if s[i] != t[i] then
            s[i] = "01"[v % 2]
            v += 1
        end
    end
    if v % 2 == 0 then
        puts s
    else
        puts "impossible"
    end
end

if __FILE__ == $0 then
    main()
end


Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.  Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.  Next line describe the second permutation in the same format.

Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.

NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this:  1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5  So he needs three moves.

n = gets.to_i
a = gets.split(' ').map { |t| t.to_i - 1 }
b = gets.split(' ').map { |t| t.to_i - 1 }
position = []
n.times { |i| position[b[i]] = i }
prev = -1
len = 0
n.times do |i|
	break if position[a[i]] < prev
        len += 1
        prev = position[a[i]]
end
puts n - len

input   = ARGF.to_a

shit    = input.shift.to_i;
first   = input.shift.split ' '
last    = input.shift.split ' '

k = j = 0

for i in 0..shit-1
  if first[j] == last[i]
    j += 1
  else
    k += 1
  end
end

puts k


Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains  distinct theorems. Besides, no theorem is mentioned in more than one card (that is,  theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 100) — the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≤ ai ≤ 100), the i-th number (1 ≤ i ≤ n) corresponds to Vasya's proficiency in the i-th theorem. The third line contains number q (0 ≤ q ≤ 100) — the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card:  integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).

Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.

NoteLet's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ x⌋ operation denotes taking integer part of real number x (rounding down).

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

vals = []
dels = []
h = {}
gets.to_i.times{
  v=0
  f = gets.split.map(&:to_i).each{|t|
    v+=a[t-1]
    dels << t-1
  }.sort.first
  h[f]=true
  vals << v/i.to_f
}
dels.each{|j| a[j]=nil }
a.compact!
a.sort!

vals += [a[0...i].inject(&:+)/i.to_f, a.reverse[0...i].inject(&:+)/i.to_f] if a.size >= i && h.size < k
vals.sort!
puts "%.7f %.7f" % [vals[0], vals[-1]]

n, m = gets.split.map(&:to_i)
l = n / m
a = gets.split.map(&:to_f)
c = []
gets.to_i.times do
    b = gets.split.map{|_| _.to_i - 1}
    next unless a[b[0]]
    c << b.map{|_| a[_]}
    b.each{|_| a[_] = nil}
end
a.compact!
if a.size > n - m * l
    a.sort!
    c << a[0, l] << a.reverse[0, l]
end
c.map!{|_| _.inject(&:+)}
puts "#{c.min / l} #{c.max / l}"

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

vals = []
dels = []
gets.to_i.times{
  v=0
  gets.split.map(&:to_i).each{|t|
    v+=a[t-1]
    dels << t-1
  }
  vals << v/i.to_f
}
dels.each{|j|
  a[j]=nil
}
a.compact!
a.sort!

vals += [a[0...i].inject(&:+)/i.to_f, a.reverse[0...i].inject(&:+)/i.to_f] if a.size >= i
vals.sort!
puts "%.7f %.7f" % [vals[0], vals[-1]]

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

vals = []
dels = []
gets.to_i.times{
  v=0
  gets.split.map(&:to_i).each{|t|
    v+=a[t-1]
    dels << t-1
  }
  vals << v/i.to_f
}
dels.each{|j| a[j]=nil }
a.compact!
a.sort!

vals += [a[0...i].inject(&:+)/i.to_f, a.reverse[0...i].inject(&:+)/i.to_f] if a.size >= i && vals.size < k
vals.sort!
puts "%.7f %.7f" % [vals[0], vals[-1]]

n, m = gets.split.map(&:to_i)
m = n / m
a = gets.split.map(&:to_f)
c = []
gets.to_i.times do
    b = gets.split.map{|_| _.to_i - 1}
    next unless a[b[0]]
    c << b.map{|_| a[_]}
    b.each{|_| a[_] = nil}
end
a.compact!
if a.size >= m
    a.sort!
    c << a[0, m] << a.reverse[0, m]
end
c.map!{|_| _.inject(&:+)}
puts "#{c.min / m} #{c.max / m}"

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_f)
c = []
gets.to_i.times do
    b = gets.split.map{|_| _.to_i - 1}
    next unless a[b[0]]
    c << b.map{|_| a[_]}
    b.each{|_| a[_] = nil}
end
a.compact!
if a.size > n - n / m * m
    a.sort!
    m = n / m
    c << a[0, m] << a.reverse[0, m]
end
c.map!{|_| _.inject(&:+)}
puts "#{c.min / m} #{c.max / m}"


You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?

The first line of the input contains single integer number n (1 ≤ n ≤ 1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.

The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.

n = gets.to_i
p = [-9e9]
n.times.map{gets.split.map(&:to_i).sort.reverse}.sort.each do |a,b|
	next if b <= p[-1]
	p << a
end
p p.size - 1
puts p[1..-1] * ' '

n=gets.to_i;s=[-9e9];n.times.map{gets.split.map(&:to_i).sort.reverse}.sort.each{|x,y|s<<x if y>s[-1]};p s.size-1;$><<s[1..-1]*' '

class Point
  attr_reader :n, :x

  def endo?
    @end
  end

  def begin?
    !@end
  end

  def initialize(n, x, endo)
    @n = n
    @x = x
    @end = endo
  end

  def <=>(other)
    return x - other.x if x != other.x
    return (endo? ? 1 : 0) - (other.endo? ? 1 : 0)
  end
end

n = gets.to_i
a = []
n.times do |i|
  x, y = *gets.split(' ').map { |x| x.to_i }
  x, y = y, x if x > y
  a << Point.new(i*2, x, false)
  a << Point.new(i*2+1, y, true)
end

done = Array.new(n, false)
stack = []
pts = []

a.sort.each do |p|
  next if done[p.n / 2]
  if p.begin?
    stack << p
    next
  end

  pts << p.x

  stack.each do |visited|
    done[visited.n / 2] = true
  end

  stack.clear
end

puts pts.size
puts pts.join(' ')


An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.The root of vertex v of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex v moving along the edges of the weighted oriented forest. We denote the root of vertex v as root(v).The depth of vertex v is the sum of weights of paths passing from the vertex v to its root. Let's denote the depth of the vertex v as depth(v).Let's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are n performed operations of adding. The i-th (i > 0) adding operation is described by a set of numbers (k,  v1,  x1,  v2,  x2,  ... ,  vk,  xk) and means that we should add vertex number i and k edges to the graph: an edge from vertex root(v1) to vertex i with weight depth(v1) + x1, an edge from vertex root(v2) to vertex i with weight depth(v2) + x2 and so on. If k = 0, then only vertex i is added to the graph, there are no added edges.Your task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo 1000000007 (109 + 7).

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of operations of adding a vertex. Next n lines contain descriptions of the operations, the i-th line contains the description of the operation of adding the i-th vertex in the following format: the first number of a line is an integer k (0 ≤ k ≤ i - 1), then follow 2k space-separated integers: v1, x1, v2, x2, ... , vk, xk (1 ≤ vj ≤ i - 1, |xj| ≤ 109).  The operations are given in the order, in which they should be applied to the graph. It is guaranteed that sum k of all operations does not exceed 105, also that applying operations of adding vertexes does not result in loops and multiple edges.

Print a single number — the sum of weights of all edges of the resulting graph modulo 1000000007 (109 + 7).

NoteConside the first sample: Vertex 1 is added. k = 0, thus no edges are added. Vertex 2 is added. k = 0, thus no edges are added. Vertex 3 is added. k = 1. v1 = 2, x1 = 1. Edge from vertex root(2) = 2 to vertex 3 with weight depth(2) + x1 = 0 + 1 = 1 is added.  Vertex 4 is added. k = 2. v1 = 1, x1 = 5. Edge from vertex root(1) = 1 to vertex 4 with weight depth(1) + x1 = 0 + 5 = 5 is added. v2 = 2, x2 = 2. Edge from vertex root(2) = 3 to vertex 4 with weight depth(2) + x1 = 1 + 2 = 3 is added. Vertex 5 is added. k = 1. v1 = 1, x1 = 2. Edge from vertex root(1) = 4 to vertex 5 with weight depth(1) + x1 = 5 + 2 = 7 is added. Vertex 6 is added. k = 1. v1 = 3, x1 = 4. Edge from vertex root(3) = 5 to vertex 6 with weight depth(3) + x1 = 10 + 4 = 14 is added.The resulting graph is shown on the pictore below:

n = gets.to_i

M = 1000000007

$u = [0]*(n+1)
$q = []
(n+1).times do $q << [] end
$w = [0]*(n+1)
$d = [0]*(n+1)
$c = [0]*(n+1)
$s = [0]*(n+1)

m = 0

def fnd(i)
  r = i;
  while i!=$u[i] do i=$u[i] end
  while r!=$u[r] do
    t = $u[r]
    $u[r] = i
    r = t
  end
  return i
end

def merge(i, j)
  i = $d[i]
  j = $d[j]
  if $s[i]<$s[j] then tt=i;i=j;j=tt; end
  $s[i] = $s[i]+$s[j]

  for k in $q[j]
    $q[i] << k
    $w[k] = $w[k]+$c[j]-$c[i]+M
    $d[k] = i
  end
  return i
end

ans = 0
for i in 1..n
  $u[i] = $d[i] = i
  $s[i] = 1
  $q[i] << i

  tl = gets.split.map(&:to_i)
  for l in 0...tl[0]
    v, x = tl[l*2+1], (tl[l*2+2]+M)%M
    r = fnd(v)
    $u[r] = i

    r = $d[v]
    e = ($w[v]+$c[r]+x)%M
    ans = ans + e

    $c[r] = ($c[r]+e)%M
    h = merge(r,i)
    $w[i] = (M-$c[h])%M
  end
end

p ans%M

n = gets.to_i

M = 1000000007

$u = [0]*(n+1)
$q = []
(n+1).times do $q << [] end
$w = [0]*(n+1)
$d = [0]*(n+1)
$c = [0]*(n+1)
$s = [0]*(n+1)

m = 0

def fnd(i, u)
  r = i;
  while i!=u[i] do i=u[i] end
  while r!=u[r] do
    t = u[r]
    u[r] = i
    r = t
  end
  return i
end

def merge(i, j)
  i = $d[i]
  j = $d[j]
  if $s[i]<$s[j] then tt=i;i=j;j=tt; end
  $s[i] = $s[i]+$s[j]

  for k in $q[j]
    $q[i] << k
    $w[k] = $w[k]+$c[j]-$c[i]+M
    $d[k] = i
  end
  return i
end

ans = 0
for i in 1..n
  $u[i] = $d[i] = i
  $s[i] = 1
  $q[i] << i

  tl = gets.split.map(&:to_i)
  for l in 0...tl[0]
    v, x = tl[l*2+1], (tl[l*2+2]+M)%M
    r = fnd(v,$u)
    $u[r] = i

    r = fnd(v,$d)
    e = ($w[v]+$c[r]+x)%M
    ans = ans + e

    $c[r] = ($c[r]+e)%M
    h = merge(r,i)
    $w[i] = (M-$c[h])%M
  end
end

p ans%M

n = gets.to_i

M = 1000000007

$u = [0]*(n+1)
$q = []
(n+1).times do $q << [] end
$w = [0]*(n+1)
$d = [0]*(n+1)
$c = [0]*(n+1)
$s = [0]*(n+1)

m = 0

def fnd(i, u)
  r = i;
  while i!=u[i] do i=u[i] end
  while r!=u[r] do
    t = u[r]
    u[r] = i
    r = t
  end
  return i
end

def merge(i, j)
  i = fnd(i,$d)
  j = fnd(j,$d)
  if $s[i]<$s[j] then tt=i;i=j;j=tt; end
  $s[i] = $s[i]+$s[j]

  for k in $q[j]
    $q[i] << k
    $w[k] = $w[k]+$c[j]-$c[i]+M
  end
  $d[j] = i
  return i
end

ans = 0
for i in 1..n
  $u[i] = $d[i] = i
  $s[i] = 1
  $q[i] << i

  tl = gets.split.map(&:to_i)
  for l in 0...tl[0]
    v, x = tl[l*2+1], (tl[l*2+2]+M)%M
    r = fnd(v,$u)
    $u[r] = i

    r = fnd(v,$d)
    e = ($w[v]+$c[r]+x)%M
    ans = ans + e

    $c[r] = ($c[r]+e)%M
    h = merge(r,i)
    $w[i] = (M-$c[h])%M
  end
end

p ans%M


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

n = gets.to_i
s = gets.chomp
zero = s.count('z')
one = s.count('n')
ans = [1] * one + [0] * zero
puts ans * ' '

def read_tokens
  return gets.chomp.to_s.strip.split(' ')
end

def read_ints
  data = []
  read_tokens.each { |s|
    data.push(s.to_i)
  }
  return data
end

n = gets.chomp.to_i
s = gets.chomp.to_s
dict = {}
s.each_char { |el|
  if dict.key?(el)
    dict[el] += 1
  else
    dict[el] = 1
  end
}

zeros = dict["z"]
ones = dict["n"]
if ones != nil
  while ones > 0
    print "1 "
    ones -= 1
  end
end

if zeros != nil
  while zeros > 0
    print "0 "
    zeros -= 1
  end
end

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1220/A

gets

word = gets.chomp

z_count = 0
n_count = 0

word.each_char do |c|
  if c == 'z'
    z_count += 1
  elsif c == 'n'
    n_count += 1
  end
end

puts ("1 " * n_count + "0 " * z_count).rstrip

n = gets.to_i
a = gets.chomp.split('')
z = e = r = o = n = 0

for char in a
	case char
	when 'z'
		z += 1
	when 'e'
		e += 1
	when 'r'
		r += 1
	when 'o'
		o += 1
	when 'n'
		n += 1
	end
end

one_number = [o, n, e].min
o -= one_number
e -= one_number
zero_number = [z, e, r, o].min

one_number.times do
	print '1 '
end
zero_number.times do
	print '0 '
end

num = gets.to_i
arr = gets

n = arr.split('').select{|x| x == 'n' }.count
z = arr.split('').select{|x| x == 'z' }.count

print "#{Array.new(n, '1').join(' ')}" if n > 0
print " " if n > 0 && z > 0
print "#{Array.new(z, '0').join(' ')}" if z > 0

n = gets.to_i
s = gets.chomp
n_c = s.count('n')
z_c = s.count('z')

puts ((['1'] * n_c) + (['0'] * z_c)).join(" ")

def big(n, line)
	place = 0
	returned = ''
	n.times do
		returned << "1 " if line[place] == "n"
		place = place + 1
	end
	place = 0
	n.times do
		returned << "0 " if line[place] == "z"
		place = place + 1
	end
	returned[-1] = '' unless returned[-1] == "0" || returned[-1] == "1"
	return returned
end

n = gets.chomp.to_i
line = gets.chomp
puts(big(n, line))

n = gets
str = gets
zeros = str.count 'z'
ones = str.count 'n'

ans = []
1.upto(ones) {ans << "1"}
1.upto(zeros) {ans << "0"}

puts ans.join(" ")

n = gets.chomp.to_i
s = gets.chomp
zero = s.count("z")
one = s.count("n")
puts "1 " * one + "0 " * zero

gets
s = gets.strip
z = s.split('').count('z')
((s.size - z*4)/3).times { print '1 ' }
z.times { print '0 ' }

gets
s = gets.chomp

puts (Array.new(s.count('n'), '1') + Array.new(s.count('z'), '0')).join(' ')

gets
s = gets.strip
z = s.split('').count('z')
((s.size - z*4)/3).times { print 1 }
z.times { print 0 }