n,m=gets.split.map(&:to_i)
p=(m-1)*2
n.times {
  s,f,t=gets.split.map(&:to_i)
  if s==f
    puts t
  else
    base= (t/p)*p
    ont = [base+s-1,base+p-s+1,base+s-1+p,base+p-s+1+p].find{|i| i>=t}
    puts [base+f-1,base+p-f+1,base+f-1+p,base+p-f+1+p].find{ |i| i>=ont}
  end
}

def solve(s, f, t, m)
  lapse = 2 * (m - 1)

  # if a person is already at his destination
  # then we just return the time when he start waiting
  return t if s == f

  if s < f
    ret = s - 1
    ret += ((t - ret) / lapse.to_f).ceil * lapse if ret < t
    # same as this
    # while ret < t
    #   ret += lapse
    # end
    ret += f - s
  else
    ret = lapse - (s - 1)
    ret += ((t - ret) / lapse.to_f).ceil * lapse if ret < t
    # same as this
    # while ret < t
    #   ret += lapse
    # end
    ret += s - f
  end
  ret
end

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

n.times do
  s, f, t = gets.strip.split(' ').map(&:to_i)
  puts solve(s, f, t, m)
end

def solve(s, f, t, m)
  lapse = 2 * (m - 1)
  # if a person is already at his destination
  # then we just return the time when he start waiting
  return t if s == f

  if s < f
    ret = s - 1
    while ret < t
      ret += lapse
    end
    ret += f - s
  else
    ret = lapse - (s - 1)
    while ret < t
      ret += lapse
    end
    ret += s - f
  end
  ret
end

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

n.times do
  s, f, t = gets.strip.split(' ').map(&:to_i)
  puts solve(s, f, t, m)
end

def read_next_line
  gets.split.map { |x| x.to_i }
end

n, m = read_next_line
q = 2 * m
z = m - 1
k = 2 * z
for _ in 1..n
  s, f, t = read_next_line
  if s == f
    puts t
    next
  end
  r = t % k
  es = m - (z - r).abs
  d = r > z
  pt = es == s ? 0 : d ^ (es < s) ? (s - es).abs : (d ^= 1) ? q - (s + es) : (s + es) - 2
  pt += d ^ (f > s) ? (s -f).abs : d ? (s + f) - 2 : q - (s + f)
  puts t + pt
end

# -*- coding: utf-8 -*-

def hoge(s,f,t,m)
  return t if s==f
  p=(m-1)*2
  base= (t/p)*p
  t -= base
  base + if s < f
    #up
    if t<=s-1
      f-1
    else
      p+f-1
    end
  else
    #down
    if t<=p-s+1
      p-f+1
    else
      p-f+1 + p
    end
  end
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  r = hoge(s,f,t,m)
  puts r
}

# -*- coding: utf-8 -*-
def f(s,f,t,m)
  return t if s==f
  p=(m-1)*2
  base= (t/p)*p
  ont = [base+s-1,base+p-s+1,base+s-1+p,base+p-s+1+p].find{|i| i>=t}
  [base+f-1,base+p-f+1,base+f-1+p,base+p-f+1+p].find{ |i| i>=ont}
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  puts f(s,f,t,m)
}

def calctime(m, s, f, t)
  if s < f
    wk = s - 1
  else
    wk = (m-1) + (m-s)
  end
  while true
    break if t <= wk
    wk += (m-1)*2
  end
  return wk + (s-f).abs
end
n, m = gets.chomp.split(/ /).map!{|x| x.to_i}
for i in 0..n-1
  s,f,t = gets.chomp.split(/ /).map!{|x| x.to_i}
  ret = t
  if s != f
    ret = calctime(m,s,f,t)
  end
  puts ret
end

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts t
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

def solve
  n, m = gets.strip.split(' ').map(&:to_i)
  m -= 1
  n.times do
    s, f, t = gets.strip.split(' ').map(&:to_i)
    r = nil
    s -= 1
    f -= 1
    if s == f
      r = t
    elsif s < f
      r = s
      while r < t
        r += 2 * m
      end
      r += (f-s).abs
    else
      r = 2 * m - s
      while r < t
        r += 2 * m
      end
      r += (f-s).abs
    end
    puts r
  end
end

solve

# -*- coding: utf-8 -*-

def hoge(s,f,t,m)
  return 0 if s==f
  p=(m-1)*2
  base= (t/p)*p
  t -= base
  base + if s < f
    #up
    if t<=s-1
      f-1
    else
      p+f-1
    end
  else
    #down
    if t<=p-s+1
      p-f+1
    else
      p-f+1 + p
    end
  end
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  r = hoge(s,f,t,m)
  puts r
}

def calctime(m, s, f, t)
  if s < f
    wk = s - 1
  else
    wk = (m-1) + (m-s)
  end
  while true
    break if t <= wk
    wk += (m-1)*2
  end
  return wk + (s-f).abs
end
n, m = gets.chomp.split(/ /).map!{|x| x.to_i}
for i in 0..n-1
  ret = 0
  s,f,t = gets.chomp.split(/ /).map!{|x| x.to_i}
  if s != f
    ret = calctime(m,s,f,t)
  end
  puts ret
end

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts 0
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

def running(ans, max, n, k, sum)
  limit = max / ans;
  ret = 0;
  1.upto(limit) do |j|
    sum[j * ans + k] ||= 0
    sum[j * ans - 1] ||= 0
    ret += sum[j * ans + k] - sum[j * ans - 1]
  end
  return ret == n;
end

def solve
  min = Float::INFINITY
  max = 0

  n, k = gets.strip.split.map(&:to_i)
  a = []
  sum = []

  gets.strip.split.each do |x|
    x = x.to_i
    a << x
    min = [x, min].min
    max = [x, max].max
    sum[x] ||= 0
    sum[x] += 1
  end

  min.upto(max+k) do |i|
    sum[i] ||= 0
    sum[i-1] ||= 0
    sum[i] += sum[i-1]
  end

  if min <= k+1
    puts min
    return
  end
  min.downto(k+1) do |i|
    if running(i, max, n, k, sum)
      puts i
      return
    end
  end
end

solve


n=gets.chomp.to_i
snack=gets.chomp.split.map{|x| x.to_i}
state=Array.new(n+1,0);
start=n
snack.each do |x|
	state[x]=1
	i=start
	while i>0
		if state[i]==2
			start-=1
		else
			if state[i]==1
				print " #{i}"
				state[i]=2#就是说在state 2下，i糖果已经被放好！
			else
				break
			end
		end
		i-=1
	end
	puts
end

#!/usr/bin/ruby
l,*a=$<.read.split.map &:to_i
h={}
a.each{|i|
	h[i]=1
	r=[]
	while h[l]
		r<<l
		l-=1
	end
	puts r*' '
}

require 'set'
n = gets.to_i
max = n
all = []
set = Set.new
nums = gets.split(' ').map{ |i| i.to_i }

n.times do |i|
  ans = []
  set << nums[i]
  #puts set.inspect
  if nums[i] == max
    while set.include?(max)
      ans << max
      set.delete(max)
      max-=1
    end
  end
  puts ans.join(' ')
end

#!/usr/bin/env ruby

n = gets.chomp.to_i
max_size = n
snack_days = gets.split.map(&:to_i)

snack_back = {}

snack_days.each do |new_snack|
  if new_snack == max_size
	print new_snack
	max_size -= 1
	while snack_back[max_size]
	  print " #{max_size}"
	  max_size -= 1
	end
  else
	snack_back[new_snack] = true
  end
  print "\n"
end


t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  flg = false
  n.times do |i|
    if a[i].even?
      p 1
      p i+1
      flg = true
      break
    end
  end
  next if flg
  if n == 1
    p -1
  else
    p 2
    puts "1 2"
  end
end

#!usr/bin/env ruby

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

count = gets.to_i

answers = []

count.times do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)

  odd_index = nil

  a.each_with_index do |num, index|
    if num % 2 == 0
      answers << 1 << index + 1
      break
    elsif n == 1
      answers << -1
      break
    else
      if odd_index.nil?
        odd_index = index + 1
      else
        answers << 2 << "#{odd_index} #{index+1}"
        break
      end
    end
  end
end

answers.each { |answer| puts answer }

#! /usr/bin/env ruby
# encoding: UTF-8

def solve
n = gets.to_i
xs = gets.split.map{|x| x.to_i }
evens = n.times.select {|i| xs[i] % 2 == 0 }
odds = n.times.select {|i| xs[i] % 2 == 1 }
if evens.size > 0 then	puts 1; puts evens.first + 1; return; end
if odds.size > 1 then  puts 2; print(odds[0]+1, ' ', odds[1]+1); puts; return; end
puts -1
end

t = gets.to_i
t.times {solve}

T = gets.to_i

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

  idx = a.index { |x| x % 2 == 0 }

  if idx
    puts 1
    puts idx + 1
  else
    odds = []

    n.times do |i|
      odds << i + 1 if a[i].odd?
    end

    if odds.size >= 2
      ans = odds.take(2)
      puts ans.size
      puts ans.join(' ')
    else
      puts -1
    end
  end
end

# coding: utf-8

t = gets.to_i
t.times {
    n = gets.to_i
    ar_odds, ar_evens = [], []
    gets.split.each_with_index { |i, index|
        i = i.to_i
        index += 1 # 1-based
        if i.odd?
            ar_odds << index
        else
            ar_evens << index
        end
    }

    if ar_evens.length > 0
        puts 1
        puts ar_evens.first
    else
        if ar_odds.length == 1
            puts -1
        else
            puts 2
            puts ar_odds[0...2].join(' ')
        end
    end

}

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  even = []
  odd = []
  a.each_with_index do |v, i|
    if v % 2 == 0
      even.push(i + 1)
    else
      odd.push(i + 1)
    end
  end
  if even.length >= 1
    puts 1
    puts even[0]
  elsif odd.length >= 2
    puts 2
    puts "#{odd[0]} #{odd[1]}"
  else
    puts -1
  end
end

#!usr/bin/env ruby

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

count = gets.to_i

answers = []

count.times do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)

  odd_index = nil

  a.each_with_index do |num, index|
    if n == 1
      answers << -1
      break
    end
    if num % 2 == 0
      answers << 1 << index + 1
      break
    else
      if odd_index.nil?
        odd_index = index + 1
      else
        answers << 2 << "#{odd_index} #{index+1}"
        break
      end
    end
  end
end

answers.each { |answer| puts answer }

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  flg = false
  n.times do |i|
    if a[i].even?
      p 1
      p i+1
      flg = true
    end
  end
  next if flg
  if n == 1
    p -1
  else
    p 2
    puts "1 2"
  end
end


t = gets.to_i
t.times do
  a, b, c = gets.split.map &:to_i
  s = [b, c/2].min
  f = [a, (b - s)/2].min
  puts (f + s)*3
end

T = gets.to_i
T.times do
  a,b,c = gets.split.map(&:to_i)
  ans = 0
  (a+1).times do |i|
    x = [a,b/2,i].min
    d,e,f = a-x, b-x*2, c
    sum = x*3
    while e > 0 && f > 1
      sum += 3
      e -= 1
      f -= 2
    end
    ans = [ans, sum].max
  end
  p ans
end

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)

  ans1 = 0
  t = [b, c/2].min
  b -= t
  c -= t * 2
  ans1 += t * 3
  t = [a, b/2].min
  a -= t
  b -= t * 2
  ans1 += t * 3

  ans2 = 0
  t = [a, b/2].min
  a -= t
  b -= t * 2
  ans2 += t * 3
  t = [b, c/2].min
  b -= t
  c -= t * 2
  ans2 += t * 3

  puts [ans1, ans2].max
end

vals = STDIN.readlines
n = vals[0].to_i
stones = []
n.times { |i|
  s = vals[i + 1].split(' ').map(&:to_i)
  stones.push(s)
}
stones.each { |stone|
  ret = 0
  while stone[2] > 1 && stone[1] >= 1
    stone[2] = stone[2] - 2
    stone[1] = stone[1] - 1
    ret += 3
  end
  while stone[1] > 1 && stone[0] >= 1
    stone[1] = stone[1] - 2
    stone[0] = stone[0] - 1
    ret += 3
  end
  p ret
}

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

def na(n=0,d=0) Array.new(n,d)end

def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end

def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def bit(n) n.to_s(2).split("").map(&:to_i) end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
ans = 0
n.times do |i|
  t = inp
  f = [t[2]/2,t[1]].min
  t[1] -= f
  s = [t[0],t[1]/2].min
  p (f+s)*3
end

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

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

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

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

t=gi
ans=[]
t.times do
  a,b,c=gsmi
  c1=min(c/2,b)
  cnt=c1
  b=b-c1
  c2=min(b/2,a)
  cnt+=c2
  ans<<cnt*3
end
puts ans

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  ans = 0
  if b < c
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
  else
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
  end
  puts ans
end

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  ans = 0
  if b <= c
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
  else
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
  end
  puts ans
end

vals = STDIN.readlines
n = vals[0].to_i
stones = []
n.times { |i|
  s = vals[i + 1].split(' ').map(&:to_i)
  stones.push(s)
}
stones.each { |stone|
  ret = 0
  while stone[2] > 1 && stone[1] > 1
    stone[2] = stone[2] - 2
    stone[1] = stone[1] - 1
    ret += 3
  end
  while stone[1] > 1 && stone[0] > 1
    stone[1] = stone[1] - 2
    stone[0] = stone[0] - 1
    ret += 3
  end
  p ret
}


t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n % 2050 != 0
    printf("-1\n")
    next
  end

  n /= 2050
  res = 0
  while n > 0
    res += n % 10
    n /= 10
  end

  printf("%d\n", res)
end

test_cases = gets.chomp.to_i
for i in 1..test_cases do
    n = gets.chomp.to_i
    if (n % 2050 == 0)
        n /= 2050
        s = n.to_s
        ans = 0
        for j in 0..s.size - 1 do
            ans += s[j].ord - '0'.ord
        end
        puts ans
    else
        puts -1
    end
end

def solution(n)
  min_number = 0
  k = 0

  while twenty_fifty_number(k) <= n
    k += 1
  end

  while k >= 0
    if n < twenty_fifty_number(k)
      k -= 1
    else
      n = n - twenty_fifty_number(k)
      min_number += 1
    end
  end

  if n == 0
    min_number
  else
    - 1
  end
end

def twenty_fifty_number(k)
  2050 * (10 ** k)
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n = gets.to_i
  res = solution(n)

  puts res
end


require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
cups = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

closed = 0
beautifully_closed = 0

markers_map = {}
markers.each do |marker|
	markers_map[marker[1]] = {-1 => 0}unless markers_map.key?(marker[1])
	markers_map[marker[1]][marker[0]] = 0 unless markers_map[marker[1]].key?(marker[0])
	markers_map[marker[1]][marker[0]] += 1
	markers_map[marker[1]][-1] += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]].key?(cups[i][0]) && markers_map[cups[i][1]][cups[i][0]] > 0
			markers_map[cups[i][1]][cups[i][0]] -= 1
			markers_map[cups[i][1]][-1] -= 1
			beautifully_closed += 1
			closed += 1
			cups.delete_at(i)
			next
		end
	end
	i += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]][-1] > 0
			markers_map[cups[i][1]][-1] -= 1
			closed += 1
		end
	end
	i += 1
end

puts "#{closed} #{beautifully_closed}"

n,m=gets.split.map(&:to_i)
markers = {}
n.times{
  color,diameter = gets.split.map(&:to_i)
  markers[diameter] ||= {}
  markers[diameter][color] ||= 0
  markers[diameter][color] += 1
}

unused_caps = {}
beautiful_closed = 0

m.times do
  color,diameter = gets.split.map(&:to_i)
  if markers[diameter] and markers[diameter][color] and markers[diameter][color] > 0
    beautiful_closed += 1
    markers[diameter][color] -= 1
  else
    unused_caps[diameter] ||= 0
    unused_caps[diameter] += 1
  end
end

closed = beautiful_closed
open_markers = {}
markers.each{|diameter,hsh|
  open_markers[diameter]=hsh.inject(0){|s,(k,v)| s+v}
}
unused_caps.each{|diameter, number|
  closed += [open_markers[diameter] || 0, unused_caps[diameter] || 0].min
}

puts "#{closed} #{beautiful_closed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}

c1h=arr[a[0]...(a[0]+a[1])].inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
m1h=arr[0...a[0]].inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
bclosed=0
c1h.each do |k,v|
  next unless m1h[k]
  bclosed+=m1h[k] >= v ? v : m1h[k]
end
c2h=arr[a[0]...(a[0]+a[1])].map{|v| v[1]}.inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
m2h=arr[0...a[0]].map{|v| v[1]}.inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
closed=0
c2h.each do |k,v|
  next unless m2h[k]
  closed+=m2h[k] >= v ? v : m2h[k]
end

puts "#{closed} #{bclosed}"

def read_array(size)
  a = []
  for _ in 1..size
    a << read_next_line
  end
  group(a)
end

def read_next_line
  gets.split.map { |x| x.to_i }
end

def group(a)
  Hash[a.inject(Hash.new { |h, e| h[e] = [] }) { |h, e| h[e[1]] << e[0]; h }.map { |k, v|
    [k, [v.inject(Hash.new(0)) { |h, e| h[e] += 1; h }, v.size]]
  }]
end

n, m = read_next_line
markers = read_array(n)
caps = read_array(m)

closed = b_closed = 0
markers.each { |d, c|
  if caps.has_key? d
    closed += [c[1], caps[d][1]].min
    c[0].each { |k, v|
      if caps[d][0].has_key? k
        b_closed += [v, caps[d][0][k]].min
      end
    }
  end
}
puts "#{closed} #{b_closed}"

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

closed = 0
beautifully_closed = 0
current_size = -1
i = 0 # marker index
j = 0 # cap index
while i < markers.length && j < caps.length
	unclosed_markers = 0
	unused_caps = 0
	current_size = markers[i][1] # or = caps[j][1]
	while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && markers[i][0] == caps[j][0]
			closed += 1
			beautifully_closed += 1
			i += 1
			j += 1
		end
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && markers[i][0] < caps[j][0]
			unclosed_markers += 1
			i += 1
		end
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && caps[j][0] < markers[i][0]
			unused_caps += 1
			j += 1
		end
		if j >= caps.length || caps[j][1] != current_size
			while i < markers.length && markers[i][1] == current_size
				unclosed_markers += 1
				i += 1
			end
		end
		if i >= markers.length || markers[i][1] != current_size
			while j < caps.length && caps[j][1] == current_size
				unused_caps += 1
				j += 1
			end
		end
	end
	closed += unclosed_markers < unused_caps ? unclosed_markers : unused_caps
	while i < markers.length && j < caps.length && markers[i][1] < caps[j][1]
		i += 1
	end
	while i < markers.length && j < caps.length && caps[j][1] < markers[i][1]
		j += 1
	end
end

puts "#{closed} #{beautifully_closed}"

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
cups = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
cups = cups.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

closed = 0
beautifully_closed = 0

markers_map = {}
markers.each do |marker|
	markers_map[marker[1]] = {-1 => 0}unless markers_map.key?(marker[1])
	markers_map[marker[1]][marker[0]] = 0 unless markers_map[marker[1]].key?(marker[0])
	markers_map[marker[1]][marker[0]] += 1
	markers_map[marker[1]][-1] += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]].key?(cups[i][0]) && markers_map[cups[i][1]][cups[i][0]] > 0
			markers_map[cups[i][1]][cups[i][0]] -= 1
			markers_map[cups[i][1]][-1] -= 1
			beautifully_closed += 1
			closed += 1
			cups.delete_at(i)
			next
		end
	end
	i += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]][-1] > 0
			markers_map[cups[i][1]][-1] -= 1
			closed += 1
		end
	end
	i += 1
end

puts "#{closed} #{beautifully_closed}"

class Array
	def my_slice_when
		arr_groups = []
		arr = [self[0]]
		i = 1
		while i < self.length
			if yield(self[i - 1], self[i])
				arr_groups.push(arr)
				arr = [self[i]]
			else
				arr.push(self[i])
			end
			i += 1
		end
		arr_groups.push(arr)
		arr_groups
	end
end

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

markers_by_size = markers.my_slice_when { |a, b| a[1] != b[1] }
caps_by_size = caps.my_slice_when { |a, b| a[1] != b[1] }

closed = 0
beautifully_closed = 0
i = 0;
markers_by_size.each do |markers_size_group|
	size = markers_size_group[0][1]
	while i < caps_by_size.length && caps_by_size[i][0][1] < size
		i += 1
	end
	break if i >= caps_by_size.length
	next if caps_by_size[i][0][1] > size
	closed += markers_size_group.length < caps_by_size[i].length ? markers_size_group.length : caps_by_size[i].length

	markers_by_color = markers_size_group.my_slice_when { |a, b| a[0] != b[0] }
	caps_by_color = caps_by_size[i].my_slice_when { |a, b| a[0] != b[0] }
	j = 0;
	markers_by_color.each do |markers_color_group|
		color = markers_color_group[0][0]
		while j < caps_by_color.length && caps_by_color[j][0][0] < color
			j += 1
		end
		break if j >= caps_by_color.length
		next if caps_by_color[j][0][0] > color
		beautifully_closed += markers_color_group.length < caps_by_color[j].length ? markers_color_group.length : caps_by_color[j].length
	end
end

puts "#{closed} #{beautifully_closed}"

n,m = gets.split.map(&:to_i)
a = Hash.new
a.default = 0
b = Hash.new
b.default = 0
c = Hash.new
c.default = 0
d = Hash.new
d.default = 0

n.times{
        tmp = gets.split.map(&:to_i)
        a[tmp[1]] += 1
        b[tmp] += 1
}
m.times{
        tmp = gets.split.map(&:to_i)
        c[tmp[1]] += 1
        d[tmp] += 1
}
u,v = 0,0

a.each{|x,y|
        u += [y, c[x]].min
}

b.each{|x,y|
        v += [y, d[x]].min
}

p u
p v

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    done << _
    beautiful += 1
    closed += 1
    h.delete m[0] if a.empty?
  end
end

done.each{|i| markers[i] = nil }

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first) && a[1].shift
    closed += 1
    h.delete a[0] if a[1].empty?
  end
end

puts "#{closed} #{beautiful}"

I = ->{gets.split.map(&:to_i)}
n, m = I[]
def r(n)
    h = {}
    n.times{
        x, y = I[]
        h[y] = h[y] || Hash.new(0)
        h[y][x] += 1
    }
    h
end
a, b, u, v = r(n), r(m), 0, 0
a.merge(b){|_, c, d|
    u += [c.size, d.size].min
    c.merge(d){|_, e, f|
        v += [e, f].min
    }
}
puts "#{u} #{v}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

beautiful = 0
closed = 0

markers.each_with_index do |m,_|
  if i = caps.index(m)
    caps.delete_at i
    markers.delete_at _
    beautiful += 1
    closed += 1
  end
end

markers.each_with_index do |m,_|
  if i = caps.index{|c| m[1] == c[1] }
    caps.delete_at i
    markers.delete_at _
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

beautiful = 0
closed = 0

markers.each do |(mc,md)|
  if i = caps.index{|(cc,cd)| mc == cc && md == cd }
    caps.delete_at i
    beautiful += 1
    closed += 1
  elsif i = caps.index{|(cc,cd)| md == cd }
    caps.delete_at i
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    beautiful += 1
    closed += 1
  end
end

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first[1]) && a.shift
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    done << _
    beautiful += 1
    closed += 1
  end
end

done.each{|i| markers[i] = nil }

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first[1]) && a.shift
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
m=arr[0...a[0]]
c=arr[a[0]...(a[0]+a[1])]

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
  arr1= c.map{|h| h[1]}.uniq
  closed += arr1.count{|val| val == pa[1]}
end
puts "#{closed} #{bclosed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
m=arr[0...a[0]].uniq
c=arr[a[0]...(a[0]+a[1])].uniq

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
end
m.map{|h| h[1]}.uniq.each do |v|
  closed += c.map{|h| h[1]}.count{|val| val == v}
end
puts "#{closed} #{bclosed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
p m=arr[0...a[0]].uniq
p c=arr[a[0]...(a[0]+a[1])].uniq

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
end
m.map{|h| h[1]}.uniq.each do |v|
  closed += c.map{|h| h[1]}.count{|val| val == v}
end
puts "#{closed} #{bclosed}"

class Array
	def my_slice_when
		arr_groups = []
		arr = [self[0]]
		i = 1
		while i < self.length
			if yield(self[i - 1], self[i])
				arr_groups.push(arr)
				arr = [self[i]]
			else
				arr.push(self[i])
			end
			i += 1
		end
		arr_groups.push(arr)
		arr_groups
	end
end

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

markers_by_size = markers.my_slice_when { |a, b| a[1] != b[1] }
caps_by_size = caps.my_slice_when { |a, b| a[1] != b[1] }

closed = 0
beautifully_closed = 0
i = 0;
markers_by_size.each do |markers_size_group|
	size = markers_size_group[0][1]
	while i < caps_by_size.length && caps_by_size[i][0][1] < size
		i += 1
	end
	break if i >= caps_by_size.length || caps_by_size[i][0][1] > size
	closed += markers_size_group.length < caps_by_size[i].length ? markers_size_group.length : caps_by_size[i].length

	markers_by_color = markers_size_group.my_slice_when { |a, b| a[0] != b[0] }
	caps_by_color = caps_by_size[i].my_slice_when { |a, b| a[0] != b[0] }
	j = 0;
	markers_by_color.each do |markers_color_group|
		color = markers_color_group[0][0]
		while j < caps_by_color.length && caps_by_color[j][0][0] < color
			j += 1
		end
		break if j >= caps_by_color.length || caps_by_color[j][0][0] > color
		beautifully_closed += markers_color_group.length < caps_by_color[j].length ? markers_color_group.length : caps_by_color[j].length
	end
end

puts "#{closed} #{beautifully_closed}"


A = ('a'..'z').to_a.join
n, m = gets.split.map(&:to_i)
s = gets.chomp
ds = m.times.map{gets.split}
a = A.dup
ds.each{|x, y| a.tr!(x + y, y + x)}
puts s.tr(A, a)

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
name = gets.chomp
design = Array.new(m)
for i in 0...m
    design[i] = gets.chomp.split
end

#puts design

replace = Array.new(26) {|i| i }
rev_replace = Array.new(26) {|i| i }

for i in 0...design.length
    x, y = design[i]
    if x != y
        x = x.ord - 97
        y = y.ord - 97
        a = rev_replace[x]
        b = rev_replace[y]
        replace[a] = y
        rev_replace[y] = a

        replace[b] = x
        rev_replace[x] = b
    end
end

for i in 0...n
    print (replace[name[i].ord - 97] + 97).chr
end

puts

# http://codeforces.com/contest/591/problem/B
# B. Rebranding

hash = {}.tap do |h|
  ('a'..'z').each { |ch| h[ch] = ch }
end
n, m = gets.chomp.split.map(&:to_i)
chars = gets.chomp.chars

m.times do
  a, b = gets.split

  tmp = hash[a]
  hash[a] = hash[b]
  hash[b] = tmp
end
invert = hash.invert
puts chars.map { |ch| invert[ch] }.join

n, m = gets.split.map(&:to_i)
s = gets.chomp
ds = m.times.map{gets.split}
a = ('a'..'z').to_a
ds.each do |x, y|
  26.times do |i|
    if a[i] == x
      a[i] = y
    elsif a[i] == y
      a[i] = x
    end
  end
end
n.times do |i|
  s[i] = a[s[i].ord - 'a'.ord]
end
puts s

n, m = gets.split.map(&:to_i)
str = gets.chomp
str1 = str.clone
result, uniq = [], []
while str1.size > 0 do
  uniq << str1[0]
  str1.delete!(str1[0])
end
uniq_arr = Array.new(uniq.length){ Array.new }
i = 0
str.each_char do |s|
  uniq.each_with_index do |u, index|
    if s == u
      uniq_arr[index] << i
      break
    end
  end
  i += 1
end
(1..m).each do |i|
  x, y = gets.split
  next if x == y
  i = 0
  uniq.each do |c|
    uniq[i] = y if c == x
    uniq[i] = x if c == y
    i += 1
  end
end
uniq.each_with_index do |u, index|
  uniq_arr[index].each do |i|
    result[i] = u
  end
end
puts result.join()

class Solver
	def main
		n, m = gets.split.map { |s| s.to_i }
		str = gets

		pos = Array.new(128) { |id, v| v = id }
		to = Array.new(128) { |id, v| v = id }
		m.times do
			a, b = gets.split.map { |c| c.ord }
			to[pos[a]], to[pos[b]] = to[pos[b]], to[pos[a]]
			pos[a], pos[b] = pos[b], pos[a]
		end

		n.times do |i|
			print to[str[i].ord].chr
		end
		print ?\n

	end
end

Solver.new.main

n = gets.split(' ')[1].to_i
s = gets
hash = {}
"a".upto("z") { |s| hash[s] = s }
n.times do
    a = gets.split(' ')
    k1 = hash.key(a[0])
    k2 = hash.key(a[1])
    tmp = hash[k1]
    hash[k1] = hash[k2]
    hash[k2] = tmp
end

hash.each { |key, value|
    s.gsub!(key, value.upcase)
}

puts s.downcase

n = gets.split(' ')[1].to_i
s = gets
hash = {}
n.times do
    a = gets.split(' ')
    hash[a[0]] = a[1]
    hash[a[1]] = a[0]
end

hash.each { |key, value|
    s.gsub!(key, value.upcase)
}

puts s.downcase

n = gets.split(' ')[1].to_i
s = gets
hash = {}
"a".upto("z") { |s| hash[s] = s }
n.times do
    a = gets.split(' ')
    tmp = hash[a[0]]
    hash[a[0]] = hash[a[1]]
    hash[a[1]] = tmp
end

hash.each { |key, value|
    s.gsub!(key, value)
}

puts s

n = gets.split(' ')[1].to_i
s = gets
n.times do
    a = gets.split(' ')
    s.gsub!(a[0], a[1])
end

puts s

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
name = gets.chomp.split("")
design_request = []
for i in 0...m
    design_request[i] = []
    design_request[i] = gets.chomp.split
end
design = []
for i in 0...m
    if design_request[i][0] != design_request[i][1]
        design.push(design_request[i])
    end
end

l = design.length
x = design[0][0]
y = design[0][1]
replace = [design[0], [y, x]]

for i in 1...l
    a = 0
    b = 0
    for j in 0...replace.length
        if replace[j][1] == design[i][0]
            replace[j][1] = design[i][1]
            a = 1
            break
        end
        if replace[j][1] == design[i][1]
            replace[j][1] = design[i][0]
            b = 1
        end
    end
    if a == 0
        replace.push(design[i])
    end
    if b == 0
        replace.push([design[i][1], design[i][0]])
    end
end

for i in 0...n
    for j in 0...replace.length
        if name[i] == replace[j][0]
            name[i] = replace[j][1]
            break
        end
    end
end
print name.join
puts

l = gets.to_i
p = gets.to_i
q = gets.to_i

puts l * ( p * 1.0 / (p + q) )


t = gets.to_i

t.times do
  n = gets.to_i
  sum = ((1 + n)*n)/2
  step = 1
  while step <= n
    sum -= 2*step
    step *= 2
  end
  puts(sum)
end

t = gets.to_i

t.times do
  n = gets.to_i
  sum = ((1 + n)*n)/2
  n = 1 + Math.log(n,2).to_i
  sum -= 2 * (2**n - 1)
  puts(sum)
end

class Solver
	def main
		n = gets.to_i
		ans = n * (n + 1) / 2
		tmp = 1
		while tmp <= n do
			ans -= 2 * tmp
			tmp *= 2
		end
		puts ans
	end
end

case_cnt = gets.to_i
case_cnt.times do
	Solver.new.main
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = (1 + n) * n / 2
  x = 1
  while x <= n do
    a -= 2 * x
    x *= 2
  end
  puts a
end

#!/usr/bin/ruby
def solve(n)
	i=1
	i*=2 while i*2<=n
	n*(n+1)/2-2*(i*2-1)
end
puts gets.to_i.times.map{solve(gets.to_i)}

#!/usr/bin/env ruby

	t=gets.chomp.to_i
	i=0
	while i<t do
		n = gets.chomp.to_i
		ans = n*(n+1)/2
		j=1
		while j<=n do
			ans-=2*j
			j*=2
		end
		puts ans
		i+=1
	end

c = gets.chomp.to_i
for i in 1..c do
  n = gets.chomp.to_i
  sum = (n * (n + 1))/2
  i = 1
  while(i <= n) do
    sum -= 2 * i
    i *= 2
  end
  puts sum
end

t = gets.to_i
t.times do
  n = gets.to_i
  sum = n * (n + 1) / 2
  power = 1
  while power <= n do
    sum = sum - power * 2
    power = power * 2
  end
  puts sum
end

# c598-A

def tricky_sum(n)
	p = Math.log(n,2).to_i
	n * (n+1) / 2 - 2 ** (p+2) + 2
end

t = gets.to_i
t.times do
	puts tricky_sum(gets.to_i)
end

#! ruby
# Codefouces My Practice
# author: Leonardone @ NEETSDKASU

t = gets.to_i

b = []

x = 1
e = 10 ** 9
while x < e
    b << x
    x <<= 1
end

t.times do
    n = gets.to_i
    s1 = (n * (n + 1)).div(2)
    s2 = b.take_while{|e| e <= n}.inject(:+) * 2
    puts (s1 - s2)
end

l=gets.chomp.to_i
p=[]
0.upto(l-1)	{|i| p[i]=gets.chomp.to_i}

def Ans(a)
	k=(a*(a+1))/2-(2*(2**((Math.log(a,2).to_i+1))-1))
	return k
end
0.upto(l-1){|i|  puts Ans(p[i])}

def fn(n); ap(n) - gp(Integer(Math.log2(n))+1)*2; end
def gp(n); 2**n-1; end
def ap(n); n * (n + 1) / 2 ; end

n = Integer(gets)
(1..n).each{|a| puts fn(Integer(gets))}

n=gets.chomp.to_i

a=0
data=[]
while a<n
	b=gets.chomp.to_i
	data.push(b)
	a+=1
end

data.each do |item|
	arif=item*(item+1)/2
	k=Math.log(item, 2).to_i
	geom=(1-2**(k+1))/(-1)
	sum=arif-2*geom
	puts sum
end

#!/usr/bin/env ruby

t = gets.to_i

def sumPowerOf2(lessOrEqThan)
  sum = 0
  (0..10**10).each do |num|
    powerOf2 = 2**num
    if powerOf2 > lessOrEqThan
      return sum
    end

    sum += powerOf2
  end
end

t.times.each do
  n = gets.to_i

  sum = (n*(n+1)/2) - (2*sumPowerOf2(n))

  puts sum
end

n=gets.to_i

n.times{
	ans=0
	a=gets.to_i
	ans=a*(a+1)/2
	b=1
	while b<=a
		ans-=(b*2)
		b*=2
	end
	puts ans
}

def sum_of_two(n)
  r, x = 0, 1
  while x <= n
    r += x
    x *= 2
  end
  r
end
t = gets.to_i
(0...t).each do |i|
  n = gets.to_i
  v = n * (n + 1) / 2
  puts v - sum_of_two(n) * 2
end

gets.to_i.times do
  n = gets.to_i
  res = n*(n+1)/2
  i = 1
  while i <= n do
    res -= 2*i
    i *= 2
  end
  puts res
end

# coding: utf-8

t = gets.to_i
t.times {
    n = gets.to_i
    sum = (n*(n+1))/2
    powersum = 0
    i = 0
    loop {
        power = 1 << i
        if power <= n
            powersum += power
            i += 1
        else
            break
        end
    }

    puts sum - 2*powersum
}

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  s = n * (n + 1) / 2
  m = 1
  while m <= n
    s -= 2 * m
    m <<= 1
  end
  puts s
end

num = gets.chomp.to_i

num.times do
  n = gets.chomp.to_i
  res = (1 + n) * n / 2
  (Math.log2(n).to_int+1).times do |n|
    res -= 2 * (2 ** (n))
  end
  puts res
end

t = gets.chomp.to_i
for i in 1..t
	n = gets.chomp.to_i
	k = (Math.log(n) / Math.log(2)).floor + 2
	s = n*(n+1)/2 - 2**k+2
	puts s
end

t = gets.to_i
t.times do
  n = gets.to_i
  ans = (1 + n) * n / 2
  minus = 1
  while minus <= n
    ans -= minus * 2
    minus *= 2
  end
  puts ans
end

t = gets.to_i
t.times do
  n = gets.to_i
  minus = 0
  30.times do |i|
    break if 2 ** i > n
    minus += 2 ** i
  end
  puts (1 + n) * n / 2 - 2 * minus
end

def cal(n)
  r = (1+n)*n/2
  k = 1
  while k <= n
    r -= k * 2
    k *= 2
  end
  r
end

t = gets.to_i

(1..t).each do
  n = gets.to_i
  puts cal(n)
end

n = gets.to_i
for i in 1..n
	k = gets.to_i
	s = (k*(k+1))/2
	v = 1
	while v<=k
		s-=v*2
		v*=2
	end
	puts(s)
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  power2 = []
  snd = 1
  i = 1
  while snd <= n
    power2 << snd
    snd = 2**i
    i += 1
  end
  puts n*(n+1)/2 - 2 * power2.inject(:+)
end

#!/usr/bin/ruby

len = gets.to_i
for iter in 0..len - 1
    t = gets.to_i
    pow = (Math.log(t) / Math.log(2)).to_i
    puts t * (t + 1) / 2 - (2 ** (pow + 1) - 1) * 2
end

# c598-A

def tricky_sum(n)
	p = Math.log(n,2)
	n * (n+1) / 2 - 2 ** p + 2
end

t = gets.to_i
t.times do
	puts tricky_sum(gets.to_i)
end

# c598-A

def tricky_sum(n)
	p = Math.log(n,2).to_i
	n * (n+1) / 2 - 2 ** p + 2
end

t = gets.to_i
t.times do
	puts tricky_sum(gets.to_i)
end

t = gets.to_i

t.times do
  n = gets.to_i
  sum = ((1 + n)*n)/2
  step = 1
  while step <= n
    sum -= step
    step *= 2
  end
  puts(sum)
end


pa=Array.new
pb=Array.new
pc=Array.new
pd=Array.new

str=gets.to_s
pa=str.split
n=pa[0].to_i
m=pa[1].to_i
for i in 0..n-1
  pb[i]=gets.to_s
  pc[i]=0
end

k=0
for j in 0..m-1
  r=flag=0
  for i in 0..n-2
    if pc[i]==0 && pb[i][j]>pb[i+1][j]
      k+=1
      flag=1
      break
    elsif pc[i]==0 && pb[i][j]<pb[i+1][j]
      pd[r]=i
      r+=1
    end
  end
  if flag==0
    for h in 0..r-1
      pc[pd[h]]=1
    end
  end
end

puts k

n, m = STDIN.readline.split.map {|s| s.to_i }
words = []
n.times { words.push(STDIN.readline.strip) }
same = n.times.map { true }
previous_same = n.times.map { false }
delete = 0

m.times do |c|
  previous_same, same = same, previous_same
  (1..n-1).each do |r|
    if previous_same[r]
      a, b = words[r-1][c], words[r][c]
      if a < b
        same[r] = false
      elsif a == b
        same[r] = true
      else
        delete += 1
        (1..n-1).each {|i| same[i] = previous_same[i] }
        break
      end
    else
      same[r] = false
    end
  end
end

puts delete

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip 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){|m,e| m[e]+=1;m} end
############################################################

N, M = gis
W = ngs N

a = [false] * N

c = 0

M.times do |i|
    b = [false] * N
    ok = true
    (N - 1).times do |j|
        if a[j]
            b[j] = true
            next
        end
        case W[j][i] <=> W[j + 1][i]
        when -1
            b[j] = true
        when 1
            ok = false
            c += 1
            break
        end
    end
    a = b if ok
end

puts c

def read_ints; STDIN.gets.split.map(&:to_i); end

n, m = read_ints
b = n.times.map{gets.rstrip}
is_g = [true] + [false] * (n-1)
ans = 0

(0.. m-1).each do |j|
    if (1..n-1).all?  {|i| is_g[i] || b[i][j] >= b[i-1][j]}
        (1..n-1).each do |i|
           is_g[i] = true if b[i][j] > b[i-1][j]
        end
    else
      ans += 1
    end
end

puts ans

# 496C

require 'set'

n, m = gets.chomp.split.map &:to_i
matrix = (1..n).map { gets.chomp.chars }
count = 0
to_check = Set.new(0...n)
m.times do |i|
  checked = Set.new
  (1...n).collect do |j|
    next unless to_check.include? j
    if matrix[j][i] < matrix[j - 1][i]
      count += 1
      break
    elsif matrix[j][i] > matrix[j - 1][i]
      checked << j
    end
  end || next
  to_check -= checked
end
puts count


main = -> {
  n = gets.to_i
  a = gets.split.map(&:to_i)

  cur = 0
  while cur + 1 < n && a[cur + 1] <= a[cur]
    cur += 1
  end

  while cur + 1 < n && a[cur + 1] >= a[cur]
    cur += 1
  end

  cur + 1 == n ? "YES" : "NO"
}

t = gets.to_i
puts t.times.map{ main.call }.join("\n")

gets.to_i.times{
    gets
    climbing=0
    sinked=0
    climbed=0
    valley=1
    s=gets.split.map(&:to_i)
    (s.size-1).times {|i|
        if s[i]<s[i+1]
            if sinked==1 and climbing==0 and climbed==1
                valley=0
            end
            climbed=1
            climbing=1
        elsif s[i]>s[i+1]
            if climbing==1
                valley=0
            end
            sinked=1
            climbing=0
        end
    }
    if valley==1
        puts("YES")
    else
        puts("NO")
    end
}

=begin

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

=end

t=gets.to_i
for i in 1..t
    n =gets.to_i
    s=gets
    maks=s.split.map{|x|x.to_i}
    num=1
    inc=0
    prev=maks[0]
    for j in 1..(n-1)
        if (maks[j]>prev)
            inc=1
        elsif (maks[j]<prev)
            if (inc==1)
                num=0
            end
        end
        prev=maks[j]
    end
    if (num==1)
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times{
    gets
    x = gets.split.map &:to_i
    c = 0
    d = -1
    (x.size-1).times{|i|
        if d<0
            if x[i+1]-x[i]>0
                c+=1
                d=1
            end
        else
            if x[i+1]-x[i]<0
                c+=1
                d=-1
            end
        end
    }
    puts c<2 ? "YES" : "NO"
}


s = gets.chomp
t = Time.now
# s = 'a' * 10 ** 5
f = true
z = 0
prev = [s[0]]
prev_ind = 0
cur = s[1]
i = 2
while i <= s.size do
  if (cur == prev.last)
    # puts cur, prev.last, "1----"
    prev.pop
    cur = s[i]
    i += 1
    f = !f
  else
    if (s[i] != cur)
      prev << cur
      cur = s[i]
      i += 1
    else
      # puts s[i], cur, "2----"
      cur = s[i + 1]
      i += 2
      f = !f
    end
  end
end
if (cur == prev.last && !cur.nil? && cur != '')
  # puts prev.last, cur, "3----"
  f = !f
end
puts f ? "No" : "Yes"
# puts Time.now - t

s=gets.chomp
t=[]
s.bytes{|c|
t<<c
t.pop(2) if c==t[-2]
}
puts (s.size-t.size)/2%2>0 ? :Yes : :No

s = gets.chomp
used = Array.new(s.size,false)
l = 0
t = []
for r in 1..s.size-1
    next if l == r
    if s[l] == s[r]
        used[l] = used[r] = true
        if t.empty?
            l = r+1
        else
            l = t[-1]
            t.pop
        end
    else
        t.push(l)
        l = r
    end
end
puts ["No","Yes"][used.count(true)/2%2]

DBG = !true
s = gets.chomp
cnt = 0
a = []
for i in 0...s.size
  a.push(s[i])
  if a.size >= 2 && a[-1] == a[-2]
    a.pop
    a.pop
    cnt += 1
  end
end
puts ((cnt%2 == 1) ? "Yes" : "No")

s = gets.chomp
chars = s.split('')

count = 0
a = Array.new
chars.each { |i|
	if a[a.size - 1] != i
		a << i
	else
		a.pop()
		count += 1
	end
}
if count % 2 == 1
	puts "Yes"
else
	puts "No"
end

s=gets.chomp
t=''.dup
s.chars{|c|
t<<c
t=t[0..-3] if c==t[-2]
}
puts (s.size-t.size)/2%2>0 ? :No : :Yes

s = gets.chomp
t = Time.now
# s = 'a' * 10 ** 5
f = true
z = 0
prev = s[0]
prev_ind = 0
cur = s[1]
i = 2
while i < s.size do
  if (cur == prev)
    # puts cur, prev, "----"
    prev_ind = [prev_ind - 1, 0].max
    prev = s[prev_ind]
    cur = s[i]
    i += 1
    f = !f
  else
    if (s[i] != cur)
      prev = cur
      prev_ind = [i - 1, 0].max
      cur = s[i]
      i += 1
    else
      # puts s[i], cur, "----"
      cur = s[i + 1]
      i += 2
      f = !f
    end
  end
end
if (cur == prev && cur != '')
  # puts prev, cur, "----"
  f = !f
end
puts f ? "No" : "Yes"

s = gets.chomp
t = Time.now
# s = 'a' * 10 ** 5
f = true
z = 0
prev = [s[0]]
prev_ind = 0
cur = s[1]
i = 2
while i < s.size do
  if (cur == prev.last)
    # puts cur, prev.last, "----"
    prev.pop
    cur = s[i]
    i += 1
    f = !f
  else
    if (s[i] != cur)
      prev << cur
      cur = s[i]
      i += 1
    else
      # puts s[i], cur, "----"
      cur = s[i + 1]
      i += 2
      f = !f
    end
  end
end
if (cur == prev.last && cur != '')
  # puts prev, cur, "----"
  f = !f
end
puts f ? "No" : "Yes"

s = gets.chomp
t = Time.now
# s = 'a' * 10 ** 5
f = true
z = 0
prev = s[0]
prev_ind = 0
cur = s[1]
i = 2
while i < s.size do
  if (cur == prev)
    # puts cur, prev, "----"
    prev_ind -= 1
    prev = s[prev_ind]
    if (prev_ind < 0)
      prev_ind = 0
      prev = ''
    end
    cur = s[i]
    i += 1
    f = !f
  else
    if (s[i] != cur)
      prev = cur
      prev_ind = [i - 1, 0].max
      cur = s[i]
      i += 1
    else
      # puts s[i], cur, "----"
      cur = s[i + 1]
      i += 2
      f = !f
    end
  end
end
if (cur == prev && cur != '')
  # puts prev, cur, "----"
  f = !f
end
puts f ? "No" : "Yes"

DBG = !true
s = gets.chomp
cnt = 0
cur = 0
while cur < s.size
  if s[cur] != s[cur+1]
    cur += 1
    next
  end
  puts "loop on cur #{cur}" if DBG
  len = 1
  while 0 <= cur - len && cur+1+len < s.size &&
       s[cur-len] == s[cur+1+len]
    len += 1
  end
  cur += len+1
  cnt += len
  puts "cur #{cur} cnt #{cnt}" if DBG
end
puts ((cnt%2 == 1) ? "Yes" : "No")


require 'pp'

n, l = STDIN.gets.chomp.split(/ /).map(&:to_i)
a = STDIN.gets.chomp.split(/ /).map(&:to_i)

a.sort!

d2 = 0

(a.count-1).times do |i|
  d2 = [d2, a[i+1] - a[i]].max
end

d = [d2.to_f/2, a.first, l-a.last].max
puts d

n,l = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
arr.sort!
diff = []
(1..n-1).each do |i|
	diff << arr[i] - arr[i-1]
end

max_diff = diff.max || 0
ans = max_diff / 2.0
val = arr[0] unless arr.include?(0)
ans = val if val && val > ans

val = l - arr[-1] unless arr.include?(l)
ans = val if val && val > ans

puts ans.to_f

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

q = q.uniq.sort

r = 2 * [q[0].to_f, (l - q[-1])].max

for i in (1..q.size-1)
  if r < q[i] - q[i-1]
    r = q[i] - q[i-1]
  end
end

puts r.to_f/2

def read_ints; STDIN.gets.split.map(&:to_i); end

n, l = read_ints
a = read_ints.sort
a << -a[0] << 2 * l - a[-2]
puts a.sort.each_cons(2).map {|x| x[1] - x[0]}.max / 2.0

n, l = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i).sort
current = -a.first
a.push l + l-a.last
result = 0

until a.empty?
  result = [(a.first-current)/2.0, result].max
  current = a.shift
end

p result

# 492B

def read_next_line
  gets.chomp.split.map &:to_i
end

n, l = read_next_line
a = read_next_line.sort
b = []
(0...n - 1).each { |i| b << a[i + 1] - a[i] }
puts [a[0], l - a[-1], b.max.to_f / 2].max

n, l = gets.split.map { |x| x.to_i }
a = gets.split.map { |x| x.to_i }
a.sort!

f = [a[0] * 2, (l - a[-1]) * 2]
1.upto(n - 1) do |i|
	f << (a[i] - a[i - 1])
end

ans = f.max / 2.0
puts '%.12f' % ans

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

ans = ([a[0],l-a[n-1]].max)*1.0

i = 0
(n-1).times do
    ans = [ans,(a[i+1]-a[i])*0.5].max
    i += 1
end

puts ans

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

arr = arr.sort
res = [arr[0], l - arr[n-1]]
for i in (1...n)
    res.push((arr[i] - arr[i-1]) / 2.0)
end

p res.max

# http://codeforces.com/contest/492/problem/B
n, l = gets.chomp.split.map(&:to_i)
lanterns = gets.chomp.split.map(&:to_f).sort

arr = [lanterns.first - 0, l - lanterns.last]
lanterns.each_cons(2){ |a, b| arr << (b - a) / 2.0 }

puts arr.max

input = gets.chomp
ginp = input.split ' '

b, s = ginp.first.to_i, ginp.last.to_i

ai = gets.chomp().split(' ').map(&:to_i).sort!
max = ai[0] > (s - ai.last) ? ai[0] : (s - ai.last)
ai.each_with_index do |v, i|
  res =  ((ai[i+1] - v) / 2.0).to_f unless i == b-1
  max = res if res && res > max
end
puts max.to_f

a,b=gets.chomp.split.map(&:to_i)
c=gets.chomp.split.map(&:to_i).sort
max=2*c[0]
max=(b-c[a-1])*2 if 2*(b-c[a-1])>max
for i in 0...a-1 do
	max=c[i+1]-c[i] if c[i+1]-c[i]>max
end
puts max/2.0

n, l = gets.split.map &:to_i
arr = gets.split.map { |x| x.to_i }.sort
max_dif = 0
for i in 0..arr.size - 2
  if arr[i + 1] - arr[i] > max_dif
    max_dif = arr[i + 1] - arr[i]
  end
end
d = [arr.first, (l - arr.last), max_dif / 2.0].max
printf "%.9f",d

n, l = gets.split.map(&:to_i)
a = gets.split(" ")
a.each_index{|i| a[i]=a[i].to_i}
a.sort!
best = 0
a.each_index{|i|
  if i>0
    best = [best,a[i]-a[i-1]].max
  end
}
puts [a[0], l-a[a.size-1], best/2.0].max

n, l = gets.split.map(&:to_i)
p = gets.split.map(&:to_i).sort

diff = [0]
(1...p.length).each do |i|
    diff << p[i] - p[i - 1]
end

max = [l - p.max, diff.max / 2.0, p.min].max
puts max

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

n, l = gets.chomp.split.map(&:to_i)
p = gets.chomp.split.map(&:to_i).sort

max = -1
y =  p[0] - 0 if 0 < p[0] - 0
max = y if y != nil and max < y
y = l - p[-1] if 0 < l - p[-1]
max = y if y != nil and max < y
x = -1
p.each do |i|
  y = (i - x) / 2.0 unless x < 0
  max = y if y != nil and max < y
  x = i
end

puts "#{max}"

n,l=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_f}

x.sort!
ans=[x[0],l-x.last].max

0.upto(x.size-2){|i|
	d=(x[i+1]-x[i])/2.0
	ans=[ans,d].max
}
puts sprintf("%.10f",ans)

#!/usr/bin/env ruby -w

def main
  _, l = gets.split.map(&:to_i)
  lights = gets.split.map(&:to_i)
  puts light_radius(l, lights)
end

def light_radius(street_length, lights)
  lights.sort!

  distances = []
  distances << lights.first
  distances << street_length - lights.last

  lights.each_cons(2) do |foo, bar|
    distances << (bar - foo) / 2.0
  end

  distances.max
end

main if __FILE__ == $0

n,l = gets.chomp.split.map(&:to_i)
arr = gets.chomp.split.map(&:to_i)

res = 0
arr.sort!
if arr[0] != 0
  res = [res,arr[0]].max
end
if arr[n-1] != n
  res = [res, l - arr[n-1]].max
end

for i in 0...n-1
  res = [res,(arr[i+1]-arr[i])/2.0].max
end

puts res

n,l = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
x = 0
for i in 0...n
	x = [ a[i] - a[i - 1] , x ].max
end
x = x/2.00
puts  [ x , a[0], l-a[n-1] ].max

input = gets.chomp
ginp = input.split ' '

n, l = ginp.first.to_i, ginp.last.to_i

ai = gets.chomp().split(' ').map(&:to_i).sort!
max = ai[0] > (l - ai.last) ? ai[0] : (l - ai.last)
ai.each_with_index do |v, i|
  x =  ((ai[i+1] - v) / 2.0).to_f unless i == n-1
  max = x if x && x > max
end
puts max.to_f

def main
  n, l = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i).sort!
  ans = [a[0], l - a[-1]].max.to_f
  (1...n).each do |i|
    ans = [ans, (a[i] - a[i - 1]) * 0.5].max
  end
  ans
end

puts main

nums = gets.chomp.split
n = Integer(nums[0])
l = Integer(nums[1])
nums2 = gets.chomp.split
lanterns = Array.new
for i in 0...nums2.length
    lanterns[i] = Integer(nums2[i])
end

if n == 1
    x = lanterns[0]
    y = l - lanterns[0]
    if x >= y
        puts x
    else
        puts y
    end
else
    lanterns.sort!
    a = lanterns[0]
    c = l - lanterns[n-1]
    dis = lanterns[1] - lanterns[0]
    for i in 0...n-1
        b = lanterns[i+1] - lanterns[i]
        if b > dis
            dis = b
        end
    end
    dis = dis.to_f / 2

    max = Array.new
    max.push(a)
    max.push(dis)
    max.push(c)

    max.sort!
    puts max[2]
end

n, l = gets.split.map(&:to_i)
p = gets.split.map(&:to_i).sort

diff = [0]
(1...p.length).each do |i|
    diff << p[i] - p[i - 1]
end

max = [l - p.max, diff.max / 2.0, diff.min].max
puts max

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

n, l = gets.chomp.split.map(&:to_i)
p = gets.chomp.split.map(&:to_i).sort

max = -1.000000000
y =  p[0] - 0 if 0 < p[0] - 0
max = y if y != nil and max < y
y = l - p[-1] if 0 < l - p[-1]
max = y if y != nil and max < y
x = -1
max = -1
p.each do |i|
  y = (i - x) / 2.000000000 unless x < 0
  max = y if y != nil and max < y
  x = i
end

puts "#{max}"

n,l = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
arr.sort!
diff = []
(1..n-1).each do |i|
	diff << arr[i] - arr[i-1]
end

max_diff = diff.max || 0
ans = max_diff / 2
val = arr[0] unless arr.include?(0)
ans = val if val && val > ans

val = l - arr[-1] unless arr.include?(l)
ans = val if val && val > ans

puts ans.to_f

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

q = q.uniq.sort

r = 2 * [q[0].to_f, (l - q[-1])].max
puts r

for i in (1..q.size-1)
  if r < q[i] - q[i-1]
    r = q[i] - q[i-1]
  end
end

puts r.to_f/2


t=gets.to_i
t.times{
    n,c0,c1,h=gets.split.map &:to_i
    bin=gets.chomp
    if c0 == c1
        puts bin.size*c0
    elsif c0 < h && c1 < h
        puts bin.count("0")*c0+bin.count("1")*c1
    else
        if c0 + h < c1
            puts bin.size*c0 + bin.count("1")*h
        elsif c1 + h < c0
            puts bin.size*c1 + bin.count("0")*h
        else
            puts bin.count("0")*c0+bin.count("1")*c1
        end
    end
}

t = gets.chomp.to_i
t.times do
  n, c0, c1, h = gets.chomp.split(' ').map(&:to_i)
  s = gets.chomp.split('')
  res = 0
  s.each do |c|
    case c
    when '1'
      res += [c1, c0 + h].min
    when '0'
      res += [c0, c1 + h].min
    end
  end
  puts res
end

t=gets.to_i
t.times{
    n,c0,c1,h=gets.split.map &:to_i
    bin=gets.chomp
    if c0 == c1
        puts bin.size*c0
    elsif c0 < h && c1 < h
        puts bin.count("0")*c0+bin.count("1")*c1
    else
        if c0 + h < c1
            puts bin.size*c0 + bin.count("1")*h
        elsif c1 + h < c0
            puts bin.size*c1 + bin.count("0")*h
        end
    end
}


n=gets.to_i
a=gets.split.map &:to_i
p ((3..n).flat_map{|i|[*a.each_slice(n/i)].transpose.map{|c|c.inject:+}unless n%i>0}-[p]).max

n = gets.to_i
ar = gets.split(' ').map(&:to_i)
ans = ar.inject(:+)
(2..(n/3)).each do |d|
  if n % d == 0
    m = (0...n).each_slice(d).map{|x| x}.transpose.map{|x|
       x.map{|y| ar[y]}.inject(:+)
    }.max
    ans = [ans,m].max
  end
end
puts ans

n=gets.to_i
a=gets.split.map &:to_i
s=a.inject &:+
2.upto(n/3){|m|
next if n%m!=0
m.times{|i|
t=(i...n).step(m).map{|_|a[_]}.inject &:+
s=t if s<t
}
}
p s

n=gets.to_i
a=gets.split.map &:to_i
p ((3..n).map{|i|[*a.each_slice(n/i)].transpose.map{|c|c.inject:+}.max if n%i<1}-[p]).max

n = gets.to_i
a = gets.split.map &:to_i
p (3..n).flat_map{ |i|
    next if n % i != 0
    b = a.each_slice(n/i).to_a.transpose
    b.map{ |c| c.inject :+ }
}.compact.max

n = gets.to_i
t = gets.split(" ").map(&:to_i)
max = 0
t.each{|el| max += el}

for d in 2..n/3 do
  next if n % d != 0
  for i in 0..d-1 do
    sum = 0
    for j in 0..n / d - 1 do
      sum += t[i + j * d]
    end
    max = sum if sum > max
  end
end

puts max

$n = gets.to_i
$a = gets.split(/\s+/).map { |i| i.to_i }
$best = $a.inject(:+)

def count(start, step)
	res = 0
	while start < $n do
		res += $a[start]
		start += step
	end
	res
end

def solve(step)
	step.times do |i|
		cur = count(i, step)
		$best = cur if cur > $best
	end
end

(2..Math.sqrt($n).round.to_i).each do |i|
	if $n % i == 0
		solve(i) if $n/i >= 3
		solve($n/i) if i >= 3
	end
end
puts $best

$n = gets.to_i
$tis = []
gets.split(' ').each {|x| $tis.push x.to_i}

$k, $s = [], []

3.upto($n) {|x| if $n % x == 0 then $k.push x end}

$k.reverse!

$k.each do |ki|
    step = $n / ki
    dots = $n / step
    shift = 0
    step.times do
        sum = 0
        i = 0
        dots.times do
            sum += $tis[i * step + shift]
            i += 1
        end
        $s.push sum
        shift += 1
    end
end

$s.sort! {|a, b| b <=> a}
puts $s[0]

n = gets.to_i
x = gets.split.map(&:to_i)
sum, max = 0, -(2**32)
1.upto(n/3) { |i| if n%i == 0
    for j in (0...i)
        (j..n-1).step(i).map { |k| sum += x[k]}
        max = sum if max < sum
        sum = 0
      end
    end
  }
  puts max

n=gets.to_i
a = gets.split.map(&:to_i)

def go(a, s)
  ret = -1111111111111
  b = 0
  while b < s
    ans = 0
    i = b
     while i < a.size
         ans += a[i]
         i += s
     end

     ret = ans if ans > ret
     b += 1
   end
   ret
 end

ans = -111111111
1.upto(n) do |x|
    next if n % x != 0
    next if n / x < 3
    ret = go(a,x)
    ans = ret if ret > ans
end

puts ans

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
(1..n).each do |i|
  next if n / i < 3 || n % i != 0
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum

n = gets.to_i
t = gets.split.map(&:to_i)
ans = t.inject(:+)
1.upto(n / 3) do |i|
  next if n % i != 0
  i.times do |j|
    sum = j.step(n - 1, i).map{|x| t[x]}.inject(:+)
    ans = sum if sum > ans
  end
end
puts ans

n = gets.chomp.to_i
arr = gets.split.collect{|x| x.to_i}

max = 0
arr.collect{|i| max += i}

for i in (1..(n/3))
  next if n % i != 0 or n / i < 3
  for j in (0..i-1)
    sum = 0
    (0..n-1).step(i) {|idx|
      sum += arr[idx+j]
    }
    max = sum if sum > max
  end
end

puts max

n = Integer(gets.chomp)
seq = gets.chomp.split.map { |x| x.to_i }
max = seq.inject(:+)
for i in 2..n / 3
  if n % i == 0 && n / i > 2
    for j in 0..i - 1
      sum = 0
      for k in (j...n).step(i)
        sum += seq[k]
      end
      max = sum if sum > max
    end
  end
end
puts max

n=gets.to_i
a=gets.split.map &:to_i
p ((3..n).flat_map{|i|a.each_slice(n/i).inject(0){|j,k|j+k.inject(:+)}unless n%i>0}-[p]).max

n = gets.to_i
x = gets.split.map(&:to_i)
sum, max = 0, 0
1.upto(n/3) { |i| if n%i == 0
    for j in (0...i)
        (j..n-1).step(i).map { |k| sum += x[k]}
        max = sum if max < sum
        sum = 0
      end
    end
  }
  puts max

n=gets.to_i
a = gets.split.map(&:to_i)

a.sort!.reverse!

ans = 0
i = 0
while i < a.length
  break if i >= 3 and a[i] < 0
  ans += a[i]
  i += 1
end

puts ans

n=gets.to_i
a = gets.split.map(&:to_i)

def go(a, s)
  ret = 0
  b = 0
  while b < s
    ans = 0
    i = b
     while i < a.size
         ans += a[i]
         i += s
     end

     ret = ans if ans > ret
     b += 1
   end
   ret
 end

ans = -111111111
1.upto(n) do |x|
    next if n % x != 0
    next if n / x < 3
    ret = go(a,x)
    ans = ret if ret > ans
end

puts ans

n=gets.to_i
a = gets.split.map(&:to_i)

def go(a, s)
  ret = 0
  b = 0
  while b < s
    ans = 0
    i = b
     while i < a.size
         ans += a[i]
         i += s
     end

     ret = ans if ans > ret
     b += 1
   end
   ret
 end

ans = -111111111
1.upto(n) do |x|
    next if n % x != 0
    ret = go(a,x)
    ans = ret if ret > ans
end

puts ans

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
nn = 2 * n ** 0.5
(0..nn).each do |i|
  next if i != 0 && n / i < 3
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
nn = 2 * n ** 0.5
(0..nn).each do |i|
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
nn = 2 * n ** 0.5
(0..nn).each do |i|
  next if i != 0 && n / i < 2
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
nn = 2 * n ** 0.5
(1..nn).each do |i|
  next if n / i < 3
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum

n = gets.to_i
t = gets.split.map(&:to_i)
sum = t.inject(:+)
nn = 2 * n ** 0.5
(3..nn).each do |i|
  (0...i).each do |j|
    k = j
    ssum = 0
    while k < n
      ssum += t[k]
      k += i
    end
    sum = ssum if ssum > sum
  end
end
puts sum


n = gets().to_i
s = gets().chomp
cur = nil
res = 0
ans = 0
count1 = 0
s.each_char do |c|
  if c == cur
    count1+=1
  else
    res += count1 + 1 if !cur.nil?
    if !cur.nil?
      break
    end
    cur = c
    count1 = 0
  end
end
ans += res
res = 0
cur = nil
count = 0
s.reverse.each_char do |c|
  if c == cur
    count+=1
  else
    res += count + 1 if !cur.nil?
    if !cur.nil?
      break
    end
    cur = c
    count = 0
  end
end
ans += res
if (s[0] == s[-1])
  ans += (count + 1) * (count1 + 1)
end

puts (ans + 1) % 998244353

N = gets.to_i
S = gets.chomp.split("").map &:intern
Mod = 998244353
ans = 1
H,T = S[0],S[-1]
mh = S.index{ |c| c != H }
mt = N - S.rindex{ |c| c != T } - 1
ans = (ans + mh) % Mod
ans = (ans + mt) % Mod
if S[0] == S[-1]
  ans = (ans + mh*mt) % Mod
end
p ans

n = gets.to_i
s = gets.strip
i = 1
while i < s.size
    break if s[i] != s[i - 1]
    i += 1
end
j = s.size - 2
j = s.size - 1 if i == s.size
while j >= 0 && j >= i
    break if s[j] != s[j + 1]
    j -= 1
end

nx = i
ny = s.size - 1 - j

ans = nx + ny + 1
ans = (1 + nx)*nx/2 if s[0] == s[-1]
ans = (1 + nx)*(1 + ny) if i <= j && s[0] == s[-1]
p ans%998244353

n = gets().to_i
s = gets().chomp
cur = nil
res = 0
ans = 0
count1 = 0
s.each_char do |c|
  if c == cur
    count1+=1
  else
    res += count1 + 1 if !cur.nil?
    if !cur.nil?
      break
    end
    cur = c
    count1 = 0
  end
end
ans += res
res = 0
cur = nil
count = 0
s.reverse.each_char do |c|
  if c == cur
    count+=1
  else
    res += count + 1 if !cur.nil?
    if !cur.nil?
      break
    end
    cur = c
    count = 0
  end
end
ans += res
if (s[0] == s[-1])
  ans += (count + 1) * (count1 + 1)
end

puts ans + 1


n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i).sort if m>0
flag=0
m.times do |i|
	if a[i]==1 || a[i]==n
		flag=1;
		break;
	elsif i>1 && a[i-1]==a[i]-1 && a[i-2]==a[i]-2
		flag=1;
		break;
	end
end
puts (flag==0) ? "YES" : "NO"

n,m = gets.split(" ").map(&:to_i)
if m != 0
	dirty = gets.split(" ").map(&:to_i)
	dirty.sort!
	ans = true
	dirty.each_cons(3) do |a,b,c|
		# puts "ele #{a} #{b} #{c}"
		# puts "diff #{b - a == 0 && c - b == 0}"
		if b - a == 1 && c - b == 1
			ans = false
			break
		end
	end
	ans = false if dirty.include?(1) || dirty.include?(n)
	puts ans ? "YES" : "NO"
else
	puts "YES"
end

n, m = gets.split.map(&:to_i)
if m==0
    puts "YES"
    exit
end
a = gets.split.map(&:to_i).sort

b = true

(2..m-1).each do |i|
   if a[i-2]+2 == a[i]
      b = false
      break
   end
end

puts a.first != 1 && a.last !=n && b ? "YES" : "NO"

def can(n, m, d)
    return true if m == 0
    return false if d[0] == 1 or d[m - 1] == n
    0.upto(m - 3) do |i|
        break if i + 2 >= m
        return false if d[i] + 1 == d[i + 1] and d[i + 1] + 1 == d[i + 2]
    end
    return true
end

n, m = *gets.split.map(&:to_i)
d = (m == 0) ? [] : gets.split.map(&:to_i).sort

puts can(n, m, d) ? "YES" : "NO"

require 'set'

n,m=gets.split.map(&:to_i)
if m > 0
  a=gets.split.map(&:to_i).to_set
else
  a = Set.new
end

if a.include?(1) || a.include?(n)
  puts 'NO'
  exit
end

a.each do |x|
  if a.include?(x+1) && a.include?(x+2)
    puts 'NO'
    exit
  end
end

puts 'YES'

def read_next_line
  gets.split.map { |x| x.to_i }
end

n, m = read_next_line
if m == 0
  puts 'YES'
  exit
end

a = read_next_line.sort
if a[0] == 1 || a[m - 1] == n
  puts 'NO'
  exit
end

if a.size > 2
  for i in 0...m - 2
     if a[i] == a[i + 1] - 1 && a[i] == a[i + 2] - 2
       puts 'NO'
       exit
     end
  end
end
puts 'YES'

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

b = true

(2..m-1).each do |i|
   if a[i-2]+2 == a[i]
      b = false
      break
   end
end

puts a.first != 1 && a.last !=n && b ? "YES" : "NO"


def solve(a)
  a.each_cons(2).map{|x,y| (x-y).abs}.reduce(a.first.abs, :+)
end

gets
a = gets.split.map(&:to_i)
puts solve a

class Solver
	def main
		n = gets.to_i
		b = gets.split.map { |x| x.to_i }
		last = 0
		ans = 0
		b.each do |x|
			x -= last
			ans += x.abs
			last += x
		end
		puts ans
	end
end

Solver.new.main

n = gets.chomp.to_i
b = gets.chomp.split.map(&:to_i)
c = 0
a = b.map do |a|
  t = (a - c).abs
  c = a
  t
end
puts a.inject(0, :+)

n = gets.chomp.to_i

b = gets.chomp.split.map(&:to_i)

x = 0;
answer = 0;
b.each do |i|
  x = (i-x)
  answer += x.abs
  x= i

end

puts answer

n=gets

data=gets.chomp.split

b=[]

data.each do |item|
	b.push(item.to_i)
end

a=(b[0]).abs
for i in(0..b.length-2)
	a+=(b[i]-b[i+1]).abs
end

puts a

n = gets.chomp.to_i
as = gets.chomp.split.map(&:to_i)

puts (1...n).to_a.inject (as[0].abs) { |s, i| s += (as[i] - as[i - 1]).abs }

class Array
  def r
    self.map { |q| q.to_i }
  end
end

n = STDIN.gets.to_i

cur = 0
res = 0
STDIN.gets.split(" ").to_a.r.each do |i|
  res += (cur - i).abs
  cur = i
end

puts res

n = gets.to_i
a = [0] + gets.split.map(&:to_i)
puts n.times.map{|i| (a[i + 1] - a[i]).abs}.inject(:+)

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
e = 0
res = 0
n.times do |i|
  res += (a[i] - e).abs
  e = a[i]
end
puts res

n=gets

data=gets.chomp.split

b=[]

data.each do |item|
	b.push(item.to_i)
end

a=b[0]
for i in(0..b.length-2)
	a+=(b[i]-b[i+1]).abs
end

puts a

n = STDIN.gets.to_i

cur = 0
res = 0
n.times do
  i = STDIN.getc.to_i
  STDIN.getc
  res += (cur - i).abs
  cur = i
end

puts res


gets.to_i.times do
  a, b, n, s = gets.split(' ').map(&:to_i)

  p = [a, s.div(n)].min

  puts (s - p*n) <= b ? 'YES' : 'NO'
end

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
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
ans=[]
q.times do
  a,b,n,s=gsmi
  sum = a*n
  if sum<=s
    s-=sum
  else #sum>s
    s=s%n
  end
  ans << (s<=b ? 'YES' : 'NO')
end

puts ans

#!/usr/bin/env ruby
count = gets.chomp.to_i
answers = []
count.times do
  input = gets.chomp.split(' ').map(&:to_i)
  a = input[0] # number of n coins
  b = input[1] # number of 1 coins
  n = input[2] # value of a coins
  sum = input[3] # wanted sum

  c = sum / n

  answers <<
    if (a <= c && a * n + b >= sum) || (a > c && c * n + b >= sum)
      "YES"
    else
      "NO"
    end
end

answers.each { |answer| puts answer }

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

a = inp[0]
a.times do
  a,b,n,s = inp
  def is_able(useable_a_count, b, s, n)
    used_a_count = [(s/n), useable_a_count].min
    remnant = s - used_a_count * n
    return (remnant <= b)
  end
  puts is_able(a,b,s,n)? "YES" : "NO"
end

g = gets.chomp.to_i
g.times{
a,b,n,s = gets.split(" ").map{|x|x.to_i}
max_a = [(s/n).round,a].min*n
max_a+=b
puts (max_a>=s)?"YES":"NO"
}

g = gets.chomp.to_i
g.times{
a,b,n,s = gets.split(" ").map{|x|x.to_i}
max_a = 0
a.times{
max_a+=(max_a+n<s)?n:0
}
max_a+=b
puts (max_a>=s)?"YES":"NO"
}


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

h = Hash.new(0)
a.each { |x| h[x] += 1 }
h = h.sort_by { |k, v| v }.reverse
k, v = h.first
v = a.size - v

puts v
if v > 0
  base_pos = a.index(k)
  range = base_pos..0
  (range.first).downto(range.last).each do |i|
    if a[i] != k
      puts "#{a[i] < k ? 1 : 2} #{i+1} #{i+2}"
    end
  end

  for i in base_pos..a.size-1
    if a[i] != k
      puts "#{a[i] < k ? 1 : 2} #{i+1} #{i}"
    end
  end
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = Hash.new(0)
n.times do |i|
    b[a[i]] += 1
end
m = a[0]
b.keys.each do |i|
    m = i if b[m] < b[i]
end
ans = []
(n-1).times do |i|
    if a[i] == m && a[i+1] != m
        if a[i] > a[i+1]
            ans << [1,i+2,i+1]
        else
            ans << [2,i+2,i+1]
        end
        a[i+1] = m
    end
end
(n-1).downto(1) do |i|
    if a[i] == m && a[i-1] != m
        if a[i] > a[i-1]
            ans << [1,i,i+1]
        else
            ans << [2,i,i+1]
        end
        a[i-1] = m
    end
end
puts ans.size
ans.each do |arr|
    puts arr.join(" ")
end

gets.chomp
a = gets.chomp.split(" ").map(&:to_i)
print "a: #{a}\n"

h = Hash.new(0)
a.each { |x| h[x] += 1 }
h = h.sort_by { |k, v| v }.reverse
k, v = h.first
v = a.size - v

puts v
if v > 0
  base_pos = a.index(k)
  range = base_pos..0
  (range.first).downto(range.last).each do |i|
    if a[i] != k
      puts "#{a[i] < k ? 1 : 2} #{i+1} #{i+2}"
    end
  end

  for i in base_pos..a.size-1
    if a[i] != k
      puts "#{a[i] < k ? 1 : 2} #{i+1} #{i}"
    end
  end
end


def solution
  countOfCase = gets.chomp.to_i
  data = []
  countOfCase.times do
    temp = gets.chomp
    data.push temp.split(' ').map(&:to_i)
  end
  data.each do |elem|
    n, s = elem[0], elem[1]
    if (n === 0)
      puts 0
    elsif (s <= n)
      puts s
    else
      base = s / n
      count = s % n
      puts (n - count) * base * base + count * (base + 1) * (base + 1);
    end
  end
end

solution

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b = inp
  c = r_up(b,a)
  d = c * a - b
  p c**2*(a-d) + (c-1)**2*d
end

def squareSum(n, value)
  [*1..n].inject(0) { |sum, i| sum += value * value }
end

def solution
  countOfCase = gets.chomp.to_i
  data = []
  countOfCase.times do
    temp = gets.chomp
    data.push temp.split(' ').map(&:to_i)
  end
  data.each do |elem|
    n, s = elem[0], elem[1]
    if (n === 0)
      puts 0
    elsif (s / n <= 1)
      puts 1
    else
      advance = s % n
      normal = n - advance
      value = s / n
      puts squareSum(normal, value) + squareSum(advance, value + 1)
    end
  end
end

solution

def squareSum(n, value)
  [*1..n].inject(0) { |sum, i| sum += value * value }
end

def solution
  countOfCase = gets.chomp.to_i
  data = []
  countOfCase.times do
    temp = gets.chomp
    data.push temp.split(' ').map(&:to_i)
  end
  data.each do |elem|
    n, s = elem[0], elem[1]
    if (n === 0)
      puts 0
    elsif (s <= n)
      puts 1
    else
      advance = s % n
      normal = n - advance
      value = s / n
      puts squareSum(normal, value) + squareSum(advance, value + 1)
    end
  end
end

solution

def solution
  countOfCase = gets.chomp.to_i
  data = []
  countOfCase.times do
    temp = gets.chomp
    data.push temp.split(' ').map(&:to_i)
  end
  data.each do |elem|
    n, s = elem[0], elem[1]
    if (n === 0)
      puts 0
    elsif (s <= n)
      puts 1
    else
      base = s / n
      count = s % n
      puts (n - count) * base * base + count * (base + 1) * (base + 1);
    end
  end
end

solution


n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
if k < n + 1 || n <= 4
  puts -1
else
  seq_1 = [a[0], a[2]] + ( (1..n).to_a - a ) + [a[3], a[1]]
  seq_2 = seq_1[0..1].reverse + seq_1[2..-3] + seq_1[-2..-1].reverse
  puts seq_1.join(' ')
  puts seq_2.join(' ')
end


gets
x=gets.split.map{|e| e.to_i}.reverse
hs={}
ans=-1
x.each{|e|
	if !hs.key?(e)
		ans=e
		hs[e]=0
	end
}
puts ans

require 'Set'

n = gets.to_i
a = gets.split().map(&:to_i)
s = a.uniq.length

was = Set.new
ans = -1
for i in a.reverse
    unless was.length == s
        if !was.include?(i)
            was.add(i)
            ans = i
        end
    end
end

puts ans

n = gets.to_i
a = gets.split.collect(&:to_i)
#s = "2 1 2 2 4 1"
#a = s.split.collect(&:to_i)
b = Array.new(2000001) { |i| 10000000  }

a.each_index{|t|
	b[a[t]] = t
}
#puts b
puts a[b.min]


gets
while line = gets
  n, a, b = line.split.map(&:to_i)
  check = lambda do
    if a == 1
      return a <= n && a % b == n % b
    end
    loop.reduce(1) do |s|
      return true if s % b == n % b
      return false if s > n / a
      s * a
    end
  end
  puts check.call ? 'Yes' : 'No'
end

def res
  return "Yes" if $n == 1
  sh = [1]
  x = $a
  #count = 0
  until x > $n or $a == 1
    return "Yes" if $n == x
    # count += 1
    sh.push x
    x *= $a
  end
  #puts "#{sh}   #{$n}   -- #{count}"
  sh.each { |k|
    x = $n - k
    return "Yes" if x % $b == 0
  }
  return "No"
end

t = gets.to_i
t.times { |u|
  $n, $a, $b = gets.chomp.split(" ").map(&:to_i)
  puts res
}

gets
while line = gets
  n, a, b = line.split.map(&:to_i)
  check = lambda do
    loop.reduce(1) do |s|
      return true if s % b == n % b
      return false if s > n / a || a == 1
      s * a
    end
  end
  puts check.call ? 'Yes' : 'No'
end

gets.to_i.times do
  n,a,b=gets.split.map(&:to_i)
  r=n%b
  if n==1
    puts "Yes"
  elsif b==1
    puts "Yes"
  elsif a==1
    if r==1
      puts "Yes"
    else
      puts "No"
    end
  else
    x=1
    f=false
    while x<=n
      if x%b==r
        puts "Yes"
        f=true
        break
      end
      x*=a
    end
    puts "No" if !f
  end
end

gets
while line = gets
  n, a, b = line.split.map(&:to_i)
  check = lambda do
    return n % b == 1 if a == 1
    loop.reduce(1) do |s|
      return true if s % b == n % b
      return false if s > n / a
      s * a
    end
  end
  puts check.call ? 'Yes' : 'No'
end

gets
while line = gets
  n, a, b = line.split.map(&:to_i)
  check = lambda do
    return true if a == 1
    loop.reduce(1) do |s|
      return true if s % b == n % b
      return false if s > n / a
      s * a
    end
  end
  puts check.call ? 'Yes' : 'No'
end

gets.to_i.times do
  n,a,b=gets.split.map(&:to_i)
  r=n%b
  if a==1
    if r==1
      puts "Yes"
    else
      puts "No"
    end
  elsif b==1
    puts "Yes"
  else
    x=1
    f=false
    while x<=n
      if x%b==r
        puts "Yes"
        f=true
        break
      end
      x*=a
    end
    puts "No" if !f
  end
end


n,m,k=gets.split.map(&:to_i)
h=gets.split.map(&:to_i)
holes=Array.new(n)
h.each{|i|holes[i-1]=true}
if holes[0]
	puts 1
	exit
end
pos=0
k.times{
	u,v=gets.split.map(&:to_i)
	u-=1
	v-=1
	to=0
	if u==pos
		to=v
	elsif v==pos
		to=u
	else
		next
	end
	if holes[to]
		puts to+1
		exit
	end
	pos=to
}

puts pos+1

require 'set'
n, m, k = gets.split.map(&:to_i)
if m * 20 < n then
  mm, x = gets.split.to_set, '1'
  begin
    break if mm.member?(x)
    u, v = gets.split
    if x == u
      x = v
    elsif x == v
      x = u
    end
    k -= 1
  end until k == 0
  puts(x)
else
  mm, x = [false] * (n + 1), 1
  gets.split.map(&:to_i).each {|t| mm[t] = true}
  begin
    break if mm[x]
    u, v = gets.split.map(&:to_i)
    if x == u
      x = v
    elsif x == v
      x = u
    end
    k -= 1
  end until k == 0
  puts(x)
end

n, _, k = gets.split.map(&:to_i)
h = gets.split.map(&:to_i)
ary = Array.new(n, false)
h.each {|v|
  ary[v - 1] = true;
}
cur = 0
k.times {
  if ary[cur]
    puts cur + 1
    exit 0
  end
  a, b = gets.split.map(&:to_i)
  a -= 1
  b -= 1
  if a == cur
    cur = b
  elsif cur == b
    cur = a
  end
}
puts cur + 1

n, m, k = gets.split(" ").map(&:to_i)
h = []
gets.split(" ").map(&:to_i).each {|i| h[i] = true}
cur = 1
if h[cur]
  p cur
  exit
end
k.times do
  u, v = gets.split(" ").map(&:to_i)
  if cur == u
    cur = v
  elsif cur == v
    cur = u
  end
  if h[cur]
    p cur
    exit
  end
end

p cur

(n,_,_),f,*x=$<.map{|x|x.split.map &:to_i}
ary = Array.new(n+1, false)
f.each{|v|ary[v] = true}
cur = 1
for z in x
  if ary[cur]
    p cur
    exit 0
  end
  a, b = z
  if a == cur
    cur = b
  elsif cur == b
    cur = a
  end
end
p cur

n,_,k=gets.split.map &:to_i
ary = Array.new(n+1, false)
gets.split.map(&:to_i).each{|v|ary[v] = true}
cur = 1
k.times {
  if ary[cur]
    puts cur
    exit 0
  end
  a, b = gets.split.map(&:to_i)
  if a == cur
    cur = b
  elsif cur == b
    cur = a
  end
}
puts cur

(n,_,_),f,*x=$<.map{|x|x.split.map &:to_i}
ary = [false]*(n+1)
f.each{|v|ary[v] = true}
cur = 1
for z in x
  if ary[cur]
    p cur
    exit 0
  end
  a, b = z
  if a == cur
    cur = b
  elsif cur == b
    cur = a
  end
end
p cur

require 'set'
n, m, k = gets.split.map(&:to_i)
if m * 20 < n then
  mm, x = gets.split.to_set, '1'
  begin
    break if mm.member?(x)
    u, v = gets.split
    if x == u
      x = v
    elsif x == v
      x = u
    end
    k -= 1
  end until k == 0
  puts(x)
else
  mm, x = [false] * (n + 1), 1
  gets.split.map(&:to_i).each {|x| mm[x] = true}
  begin
    break if mm[x]
    u, v = gets.split
    if x == u
      x = v
    elsif x == v
      x = u
    end
    k -= 1
  end until k == 0
  puts(x)
end


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 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'

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'


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.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

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(&: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.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

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

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.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


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'

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.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'

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

}

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

#! 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
}

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

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


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
      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

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


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
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

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


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]
}

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]
}