Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Problem F:
RabbitLunch

うさぎは昼食ににんじんとキウイを1 個ずつ食べる. うさぎはとても個性的なので, 食べるにんじんの種類もキウイの種類も同じであるような, 異なる2 匹のうさぎが存在してはならない.

にんじんは $M$ 種類ある. $i$ 種類目のにんじんは $m_i$ 個ある. キウイは $N$ 種類ある. $i$ 種類目のキウイは $n_i$ 個ある. 最大何匹のうさぎが昼食をとれるか求めよ.

$m_i$ と $n_i$ は次の漸化式を用いて生成せよ.

$m_0 = m0$

$m_{i+1} = (m_i * 58 + md )$ mod $(N + 1)$

$n_0 = n0$

$n_{i+1} = (n_i * 58 + nd )$ mod $(M + 1)$

Constraints

$M$ will be between 1 and 2,500,000, inclusive.

$N$ will be between 1 and 2,500,000, inclusive.

$m0$ and $md$ will be between 0 and $N$, inclusive.

$n0$ and $nd$ will be between 0 and $M$, inclusive.

Input

入力は以下の形式で与えられる:

$M$ $N$ $m0$ $md$ $n0$ $nd$

Output

昼食をとれるうさぎの匹数の最大値を表す整数を 1 行に出力せよ.

Sample Input 1

2 3 1 3 1 0

Sample Output 1

2

Sample Input 2

5 8 1 2 3 4

Sample Output 2

19

Solution in Ruby (judge verdict: Wrong Answer)

m, n, m0, md, n0, nd = gets.split.map(&:to_i)

degs_l = [m0]
(m - 1).times do
    degs_l << (degs_l[-1] * 58 + md) % (n + 1)
end

degs_r = [n0]
(n - 1).times do
    degs_r << (degs_r[-1] * 58 + nd) % (m + 1)
end

degs_l.sort!
degs_r.sort!

k = 0
degs_l.each do |x|
    degs_r.reject! {|y| y == 0}
    x = [x, degs_r.size].min
    k += x
    (-x..-1).each {|i| degs_r[i] -= 1}
end

p k