Problem:
Problem H: Nearest Station

うさぎがある電車のチケットをn 枚持っている. チケットにはそれぞれ0 からn − 1 までの番号がついていて, k 番のチケットを使うと, p⋅ak + q⋅bk 駅進むことができる.

うさぎは今いる駅からm 駅進んだ駅にあるニンジン食べ放題の店に行きたいが, なるべく歩く距離を短くしたい. 駅は等間隔に並んでいる. チケットを電車の上り線で進むことのみに用いるとき, うさぎは最小何駅分の徒歩で店に着けるか.

Input

1 ≤ n, m, a, b, p, q ≤ 1 000 000 000 000 (整数)

Output

うさぎは最小何駅分の徒歩で店に着けるか, その数を一行に出力せよ.

Sample Input 1

6 200 2 3 4 5

Sample Output 1

1

Sample Input 2

6 1 2 3 4 5

Sample Output 2

1

Solution in Ruby (judge verdict: Accepted)

class Array
	def accum
		ac = Array.new(size + 1)
		ac[0] = 0
		(1..size).each do |i|
			ac[i] = ac[i-1] + self[i-1]
		end
		ac
	end

	def accum!
		(1..size-1).each{|i|
			self[i] += self[i-1]
		}
		self.unshift(0)
	end

	def accum_2d
		ac = map{|r| r.accum}
		(1..size-1).each{|i|
			(1..ac[0].size-1).each{|j|
				ac[i][j] += ac[i-1][j]
			}
		}
		ac.unshift([0] * ac[0].size)
		ac
	end

	def accum_2d!
		each{|r| r.accum!}
		(1..size-1).each{|i|
			(1..self[0].size-1).each{|j|
				self[i][j] += self[i-1][j]
			}
		}
		unshift([0] * self[0].size)
	end
		
	def bsearch_first_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2 
		if pred[self[c]]
			bsearch_first_index(l, c-1, &pred) || c
		else
			bsearch_first_index(c+1, r, &pred)
		end
	end

	def bsearch_first_item(l = 0, r = size - 1, &pred)
		i = bsearch_first_index(l, r, &pred)
		i ? self[i] : nil
	end

	def bsearch_last_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2 
		if pred[self[c]]
			bsearch_last_index(c+1, r, &pred) || c
		else
			bsearch_last_index(l, c-1, &pred)
		end
	end

	def bsearch_last_item(l = 0, r = size - 1, &pred)
		i = bsearch_last_index(l, r, &pred)
		i ? self[i] : nil
	end
end

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

if a == 1 && b == 1
	k = m / (q + r)
	if k < n
		p [m - k * (q + r), (k + 1) * (q + r) - m].min
	else 
		p m - n * (q + r)
	end
	exit
end

steps = []
(0..n-1).each do |k|
	s = q*a**k + r*b**k
	steps << s
	break if s >= m
end

min = m
if steps[-1] > m
	x = steps.pop
	min = x - m if x && x - m < min
end

half1, half2 = steps.partition.with_index{|x, i| i < steps.size / 2}

subset_sums1 = [0]
(1..2**half1.size-1).each do |x|
	i = ((x - 1) ^ x).to_s(2).size - 1
	y = x - (1 << i)
	subset_sums1[x] = subset_sums1[y] + half1[i]
end
subset_sums1.uniq!
subset_sums1.sort!

subset_sums2 = [0]
(1..2**half2.size-1).each do |x|
	i = ((x - 1) ^ x).to_s(2).size - 1
	y = x - (1 << i)
	subset_sums2[x] = subset_sums2[y] + half2[i]
end

subset_sums2.each do |ss2|
	if ss2 >= m
		min = ss2 - m if ss2 - m < min
		next
	end

	i = subset_sums1.bsearch_last_index {|ss1| ss2 + ss1 <= m}
	x = subset_sums1[i] + ss2
	min = m - x if m - x < min
	if i < subset_sums1.size - 1
		x = subset_sums1[i+1] + ss2
		min = x - m if x - m < min
	end
end
p min