In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≤ n ≤ 109).

Print the requested sum for each of t integers n given in the input.

NoteThe answer for the first sample is explained in the statement.

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

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

# 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


Lindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.Consider a hexagonal tiling of the plane as on the picture below.  Nicks wishes to go from the cell marked $$$(0, 0)$$$ to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from $$$(0, 0)$$$ to $$$(1, 1)$$$ will take the exact same cost as going from $$$(-2, -1)$$$ to $$$(-1, 0)$$$. The costs are given in the input in the order $$$c_1$$$, $$$c_2$$$, $$$c_3$$$, $$$c_4$$$, $$$c_5$$$, $$$c_6$$$ as in the picture below.  Print the smallest cost of a path from the origin which has coordinates $$$(0, 0)$$$ to the given cell.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^{4}$$$). Description of the test cases follows. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$-10^{9} \le x, y \le 10^{9}$$$) representing the coordinates of the target hexagon. The second line of each test case contains six integers $$$c_1$$$, $$$c_2$$$, $$$c_3$$$, $$$c_4$$$, $$$c_5$$$, $$$c_6$$$ ($$$1 \le c_1, c_2, c_3, c_4, c_5, c_6 \le 10^{9}$$$) representing the six costs of the making one step in a particular direction (refer to the picture above to see which edge is for each value).

For each testcase output the smallest cost of a path from the origin to the given cell.

NoteThe picture below shows the solution for the first sample. The cost $$$18$$$ is reached by taking $$$c_3$$$ 3 times and $$$c_2$$$ once, amounting to $$$5+5+5+3=18$$$.

T = gets.to_i

T.times do
  y, x = gets.split.map(&:to_i)
  c = gets.split.map(&:to_i)

  if c[0] > c[1] + c[5]
    c[0] = c[1] + c[5]
  end

  if c[1] > c[0] + c[2]
    c[1] = c[0] + c[2]
  end

  if c[2] > c[1] + c[3]
    c[2] = c[1] + c[3]
  end

  if c[3] > c[2] + c[4]
    c[3] = c[2] + c[4]
  end

  if c[4] > c[3] + c[5]
    c[4] = c[3] + c[5]
  end

  if c[5] > c[0] + c[4]
    c[5] = c[0] + c[4]
  end

  cy = 0
  cx = 0
  ans = 0

  if cx < x && cy < y
    d = [x - cx, y - cy].min
    cy += d
    cx += d
    ans += c[0] * d
  end

  if x < cx && y < cy
    d = [cx - x, cy - y].min
    cy -= d
    cx -= d
    ans += c[3] * d
  end

  if cx < x
    d = x - cx
    cx += d
    ans += c[1] * d
  end

  if x < cx
    d = cx - x
    cx -= d
    ans += c[4] * d
  end

  if cy < y
    d = y - cy
    cy += d
    ans += c[5] * d
  end

  if y < cy
    d = cy - y
    cy -= d
    ans += c[2] * d
  end

  puts ans
end


This is the easy version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1'($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good?

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single line with one integer — the minimum number of operations to make $$$s$$$ good.

NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100".In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.

gets.to_i.times do
  n = gets.to_i
  a = gets.split('').map(&:to_i)
  sl = [1]
  c = 0
  1.upto(n-1) do |i|
    if a[i] != a[i-1] then
      c += 1
      sl[c] = 1
    else
      sl[c] += 1
    end
  end
  ans = 0
  r = 0
  sl.each do |l|
    if (l%2 == 1) then
      r = 1 - r
    end
    ans += r
  end
  puts ans
end


Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code:     ans = solve(l, r) % a;    if (ans <= 0)      ans += a; This code will fail only on the test with . You are given number a, help Little X to find a proper test for hack.

The first line contains a single integer a (1 ≤ a ≤ 1018).

Print two integers: l, r (1 ≤ l ≤ r < 10200) — the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.


You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk we obtain the table:acdefghjk A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.

The first line contains two integers  — n and m (1 ≤ n, m ≤ 100). Next n lines contain m small English letters each — the characters of the table.

Print a single number — the minimum number of columns that you need to remove in order to make the table good.

NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.

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

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

# 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


You are given an array $$$a[0 \dots n-1]$$$ of $$$n$$$ integers. This array is called a "valley" if there exists exactly one subarray $$$a[l \dots r]$$$ such that:  $$$0 \le l \le r \le n-1$$$,  $$$a_l = a_{l+1} = a_{l+2} = \dots = a_r$$$,  $$$l = 0$$$ or $$$a_{l-1} > a_{l}$$$,  $$$r = n-1$$$ or $$$a_r < a_{r+1}$$$. Here are three examples:  The first image shows the array [$$$3, 2, 2, 1, 2, 2, 3$$$], it is a valley because only subarray with indices $$$l=r=3$$$ satisfies the condition.The second image shows the array [$$$1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6$$$], it is a valley because only subarray with indices $$$l=0, r=2$$$ satisfies the codition.The third image shows the array [$$$1, 2, 3, 4, 3, 2, 1$$$], it is not a valley because two subarrays $$$l=r=0$$$ and $$$l=r=6$$$ that satisfy the condition.You are asked whether the given array is a valley or not.Note that we consider the array to be indexed from $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases is smaller than $$$2\cdot10^5$$$.

For each test case, output "YES" (without quotes) if the array is a valley, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteThe first three test cases are explained in the statement.

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


Two people are playing a game with a string $$$s$$$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.

The only line contains the string $$$s$$$, consisting of lowercase latin letters ($$$1 \leq |s| \leq 100\,000$$$), where $$$|s|$$$ means the length of a string $$$s$$$.

If the first player wins, print "Yes". If the second player wins, print "No".

NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into "q", then second player is unable to move, so he loses.

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
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 = 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
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
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")


Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 109) — the number of lanterns and the length of the street respectively.  The next line contains n integers ai (0 ≤ ai ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.

Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.

NoteConsider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit.

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

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 { |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}"

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

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


You are given four integers $$$n$$$, $$$c_0$$$, $$$c_1$$$ and $$$h$$$ and a binary string $$$s$$$ of length $$$n$$$.A binary string is a string consisting of characters $$$0$$$ and $$$1$$$.You can change any character of the string $$$s$$$ (the string should be still binary after the change). You should pay $$$h$$$ coins for each change.After some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character $$$0$$$ you should pay $$$c_0$$$ coins, to buy the character $$$1$$$ you should pay $$$c_1$$$ coins.Find the minimum number of coins needed to buy the string.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains four integers $$$n$$$, $$$c_{0}$$$, $$$c_{1}$$$, $$$h$$$ ($$$1 \leq n, c_{0}, c_{1}, h \leq 1000$$$). The second line of the description of each test case contains the binary string $$$s$$$ of length $$$n$$$.

For each test case print a single integer — the minimum number of coins needed to buy the string.

NoteIn the first test case, you can buy all characters and pay $$$3$$$ coins, because both characters $$$0$$$ and $$$1$$$ costs $$$1$$$ coin.In the second test case, you can firstly change $$$2$$$-nd and $$$4$$$-th symbols of the string from $$$1$$$ to $$$0$$$ and pay $$$2$$$ coins for that. Your string will be $$$00000$$$. After that, you can buy the string and pay $$$5 \cdot 10 = 50$$$ coins for that. The total number of coins paid will be $$$2 + 50 = 52$$$.

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
}


This is an interactive problem.We picked an array of whole numbers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) and concealed exactly one zero in it! Your goal is to find the location of this zero, that is, to find $$$i$$$ such that $$$a_i = 0$$$.You are allowed to make several queries to guess the answer. For each query, you can think up three distinct indices $$$i, j, k$$$, and we will tell you the value of $$$\max(a_i, a_j, a_k) - \min(a_i, a_j, a_k)$$$. In other words, we will tell you the difference between the maximum and the minimum number among $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$.You are allowed to make no more than $$$2 \cdot n - 2$$$ queries, and after that you have two tries to guess where the zero is. That is, you have to tell us two numbers $$$i$$$ and $$$j$$$ and you win if $$$a_i = 0$$$ or $$$a_j = 0$$$.Can you guess where we hid the zero?Note that the array in each test case is fixed beforehand and will not change during the game. In other words, the interactor is not adaptive.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first and only line of each test case contains an integer $$$n$$$ ($$$4 \le n \le 1000$$$) — the length of the array that we picked. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.

NoteArray from sample: $$$[1, 2, 0, 3]$$$.

gets.to_i.times do
  n = gets.to_i

  m = 4
  heap = [1, 2, 3, 4]

  query = lambda do |indices|
    puts '? ' + indices.join(' ')
    $stdout.flush
    gets.to_i
  end

  loop do
    complement = []
    heap.each do |i|
      complement << query.call(heap - [i])
    end

    d = complement.max
    heap = heap.zip(complement).filter { |h, c| c != d }.map { _1.first }

    if m == n
      heap << heap.first if heap.size < 2
      puts '! ' + heap.join(' ')
      $stdout.flush
      break
    end

    while heap.size < 4
      break unless m < n
      m += 1
      heap << m
    end

    while heap.size < 4
      (1..).each do |x|
        next if heap.include? x
        heap << x
        break
      end
    end
  end
end

gets.to_i.times do
  n = gets.to_i

  m = 4
  heap = [1, 2, 3, 4]

  query = lambda do |indices|
    puts '? ' + indices.join(' ')
    $stdout.flush
    gets.to_i
  end

  complement = []
  heap.each do |i|
    complement << query.call(heap - [i])
  end

  d = complement.max
  heap = heap.zip(complement).filter { |h, c| c != d }.map { _1.first }

  if m == n
    puts '! ' + heap.join(' ')
    $stdout.flush
    next
  end

  2.times do
    break unless m < n
    heap << m
    m += 1
  end

  if heap.size < 4
    (1..).each do |x|
      next if heap.include? x
      heap << x
      break
    end
  end
end

gets.to_i.times do
  n = gets.to_i

  max_diff = 0
  max_i = nil

  (n - 2).times do |i|
    puts "? #{i + 1} #{i + 2} #{i + 3}"
    $stdout.flush
    d = gets.to_i

    if d > max_diff
      max_diff = d
      max_i = i
    end
  end

  # Let's eliminate `max_i`.
  ans = nil
  n.times do |i|
    next if max_i <= i && i <= max_i + 2

    puts "? #{i + 1} #{max_i + 2} #{max_i + 3}"
    $stdout.flush
    d = gets.to_i

    if d == max_diff
      # Yep, `max_i` is not zero.
      ans = [max_i + 2, max_i + 3]
      break
    end
  end

  if ans
    puts '! ' + ans.join(' ')
  else
    puts "! #{max_i + 1} #{max_i + 2}"
  end
  $stdout.flush
end


After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.

First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction.

Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.

NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4.

n = gets.to_i
ary = gets.strip.split.map(&:to_i)
x, f = gets.strip.split.map(&:to_i)

ans = 0
mtv = x+f
ary.each do |v|
  t = (v-1)/mtv
  rv = v % mtv
  t += 1 if rv > x
  ans += (t*f)
end

puts ans


The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:   the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),  the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.

The first input line contains an integer n (3 ≤ n ≤ 20000) — the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti — the degree of the i-th sculpture's attractiveness ( - 1000 ≤ ti ≤ 1000). The numbers on the line are separated by spaces.

Print the required maximum sum of the sculptures' attractiveness.

NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 3.

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


You are given a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in $$$s$$$.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo $$$998244353$$$.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in $$$s$$$.

Print one integer — the number of ways modulo $$$998244353$$$ to remove exactly one substring from $$$s$$$ in such way that all remaining characters are equal.

NoteLet $$$s[l; r]$$$ be the substring of $$$s$$$ from the position $$$l$$$ to the position $$$r$$$ inclusive.Then in the first example you can remove the following substrings:   $$$s[1; 2]$$$;  $$$s[1; 3]$$$;  $$$s[1; 4]$$$;  $$$s[2; 2]$$$;  $$$s[2; 3]$$$;  $$$s[2; 4]$$$. In the second example you can remove the following substrings:   $$$s[1; 4]$$$;  $$$s[1; 5]$$$;  $$$s[1; 6]$$$;  $$$s[1; 7]$$$;  $$$s[2; 7]$$$;  $$$s[3; 7]$$$. In the third example you can remove the following substrings:   $$$s[1; 1]$$$;  $$$s[1; 2]$$$;  $$$s[2; 2]$$$.

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


Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.

The first line contains two integers n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 3000) — the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d1, d2, ..., dm (1 ≤ di ≤ n) — the numbers of the dirty stairs (in an arbitrary order).

Print "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO".

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"


Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array ai. Initially ai = 0 for every position i, so this array is not given in the input. The second line of the input contains n integers b1, b2, ..., bn ( - 109 ≤ bi ≤ 109).

Print the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for all i.

NoteIn the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1.

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 }

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

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

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


You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.

For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

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

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

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

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations arbitrary number of times (possibly, zero):  Choose a pair of indices $$$(i, j)$$$ such that $$$|i-j|=1$$$ (indices $$$i$$$ and $$$j$$$ are adjacent) and set $$$a_i := a_i + |a_i - a_j|$$$;  Choose a pair of indices $$$(i, j)$$$ such that $$$|i-j|=1$$$ (indices $$$i$$$ and $$$j$$$ are adjacent) and set $$$a_i := a_i - |a_i - a_j|$$$. The value $$$|x|$$$ means the absolute value of $$$x$$$. For example, $$$|4| = 4$$$, $$$|-3| = 3$$$.Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.It is guaranteed that you always can obtain the array of equal elements using such operations.Note that after each operation each element of the current array should not exceed $$$10^{18}$$$ by absolute value.

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

In the first line print one integer $$$k$$$ — the minimum number of operations required to obtain the array of equal elements. In the next $$$k$$$ lines print operations itself. The $$$p$$$-th operation should be printed as a triple of integers $$$(t_p, i_p, j_p)$$$, where $$$t_p$$$ is either $$$1$$$ or $$$2$$$ ($$$1$$$ means that you perform the operation of the first type, and $$$2$$$ means that you perform the operation of the second type), and $$$i_p$$$ and $$$j_p$$$ are indices of adjacent elements of the array such that $$$1 \le i_p, j_p \le n$$$, $$$|i_p - j_p| = 1$$$. See the examples for better understanding. Note that after each operation each element of the current array should not exceed $$$10^{18}$$$ by absolute value. If there are many possible answers, you can print any.

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)

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

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


Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example:  the following words have typos: "hellno", "hackcerrs" and "backtothefutttture";  the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.

The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.

Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.

def pos(ch)
	ch.ord - 'a'.ord
end

s = gets.chomp

abc = [0]
25.times{abc << 1}
abc[pos('o')] = 0
abc[pos('e')] = 0
abc[pos('i')] = 0
abc[pos('u')] = 0

ans = ""

cnt = 0
i = 2
while i < s.size
	if abc[pos(s[i])] + abc[pos(s[i - 1])] + abc[pos(s[i - 2])] == 3
		j = i
		while j < s.size && s[j] == s[i - 1]
			j += 1
		end

		if s[i - 2] == s[i - 1] && j >= i + 1
			ans << s[i-2..j-3]
			i = j
		elsif j <= i + 1
			ans << s[i-2..i-1] + " "
			i += 2
		else
			ans << s[i - 2] + " "
			i += 1
		end
	else
		if abc[pos(s[i])] + abc[pos(s[i - 1])] == 2
			ans << s[i - 2]
			i += 1
		elsif abc[pos(s[i])] == 1
			ans << s[i-2..i-1]
			i += 2
		else
			ans << s[i-2..i]
			i += 3
		end
	end
end

puts ans + s[i-2..-1]


Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \le c_i, sum_i \le 10^4$$$) — the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.

For each room print one integer — the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.

NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$.

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

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


Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.For each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.Help Vasya find the maximum number of photos he is able to watch during T seconds.

The first line of the input contains 4 integers n, a, b, T (1 ≤ n ≤ 5·105, 1 ≤ a, b ≤ 1000, 1 ≤ T ≤ 109) — the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo. Second line of the input contains a string of length n containing symbols 'w' and 'h'.  If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation. If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.

Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.

NoteIn the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.

#!/usr/bin/ruby
n, a, b, max_time = gets().split(' ').map(&:to_i)
po = gets().chars.to_a

i = 0
j = 0
t = 0
max_count = 0
while j < n
  duration = 1
  duration += a if j > 0
  duration += b if po[j] == 'w'
  break if t + duration > max_time
  t += duration
  j += 1
end

max_count = j - i
unless max_count == 0 || max_count == n
  i = n
  while i > 0 && j >= 1
    i -= 1
    duration = 1 + a
    duration += b if po[i] == 'w'

    t += duration
    while t + a*[n-i,j-1].min > max_time
      j -= 1
      t -= 1 + a
      t -= b if po[j] == 'w'
    end
    max_count = [max_count, (j-i) + n].max
  end
end

puts max_count

#!/usr/bin/ruby
n, a, b, max_time = gets().split(' ').map(&:to_i)
po = gets().chars.to_a

i = 0
j = 0
t = 0
max_count = 0
while j < n
  duration = 1
  duration += a if j > 0
  duration += b if po[j] == 'w'
  break if t + duration > max_time
  t += duration
  j += 1
end

max_count = j - i
unless max_count == 0 || max_count == n
  i = n
  while i > 0 && j >= 0
    i -= 1
    duration = 1 + a
    duration += b if po[i] == 'w'

    t += duration
    while t + a*[n-i,j-1].min > max_time
      j -= 1
      t -= 1 + a
      t -= b if po[j] == 'w'
    end
    max_count = [max_count, (j-i) + n].max
  end
end

puts max_count


Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:   There is no road between a and b.  There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.

The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).

Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d. Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.

NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.

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


Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.

In first line there is one integer n (1 ≤ n ≤ 2·105) — number of cafes indices written by Vlad. In second line, n numbers a1, a2, ..., an (0 ≤ ai ≤ 2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.

Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.

NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.

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


Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\rightarrow$$$ $$$(2,-\sqrt{5})$$$ $$$\rightarrow$$$ $$$(4,0)$$$).    Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of hops needed.

NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to $$$(2,\sqrt{5})$$$, then to $$$(4,0)$$$ for a total of two hops. Each hop has a distance of $$$3$$$, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop $$$3$$$ times is: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(4,0)$$$ $$$\rightarrow$$$ $$$(8,0)$$$ $$$\rightarrow$$$ $$$(12,0)$$$.In the third test case of the sample, Rabbit can hop from $$$(0,0)$$$ to $$$(5,0)$$$.In the fourth test case of the sample, Rabbit can hop: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(5,10\sqrt{2})$$$ $$$\rightarrow$$$ $$$(10,0)$$$.

T = gets.to_i

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

  ans = 0
  m = a.max
  c = [0, (x / m) - 1].max
  remain = x - m * c

  ans += c

  if remain % m == 0
    ans += remain / m
  else
    if a.find { |x| x == remain }
      ans += 1
    else
      ans += 2
    end
  end

  puts ans
end


There is an infinite set generated as follows:  $$$1$$$ is in this set.  If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are:  $$$1$$$,  $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set),  $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set),  $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set),  $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) — the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.

For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, $$$24$$$ is generated as follows:  $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set;  $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set;  $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.

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

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

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


Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

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


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.

T = gets.to_i

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

  if sum == 0
    puts 'NO'
  elsif sum > 0
    puts 'YES'
    puts a.reverse.join(' ')
  else
    puts 'YES'
    puts a.join(' ')
  end
end


Peter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [l1, r1] and [l2, r2], where Peter added one, the following inequalities hold: l1 ≠ l2 and r1 ≠ r2.How many distinct ways are there to make all numbers in the sequence equal h? Print this number of ways modulo 1000000007 (109 + 7). Two ways are considered distinct if one of them has a segment that isn't in the other way.

The first line contains two integers n, h (1 ≤ n, h ≤ 2000). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 2000).

Print a single integer — the answer to the problem modulo 1000000007 (109 + 7).

n, h = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
mod = 1000000007
dp = Array.new(n,0)
dp[0]=1
for i in 0...n do
  tdp = Array.new(n,0)
  nd = h-a[i]
  tdp[nd] = ( tdp[nd] + dp[nd] ) % mod if nd >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd] * nd ) % mod if nd-1 >= 0 && nd < n
  tdp[nd] = ( tdp[nd] + dp[nd-1] ) % mod if nd-1 >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd-1] ) % mod if nd-1 >= 0
  tdp[nd-1] = ( tdp[nd-1] + dp[nd-1] * (nd-1) ) % mod if nd-1 >= 0 && nd < n
  dp = tdp
end
puts dp[0]

n, h = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
mod = 1000000007
dp = Array.new(n,0)
dp[0]=1
for i in 0...n do
  tdp = Array.new(n,0)
  nd = h-a[i]
  tdp[nd] = ( tdp[nd] + dp[nd] ) % mod if nd >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd] ) % mod if nd-1 >= 0 && nd < n
  tdp[nd] = ( tdp[nd] + dp[nd-1] ) % mod if nd-1 >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd-1] ) % mod if nd-1 >= 0
  dp = tdp
end
puts dp[0]

n, h = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
mod = 1000000007
dp = Array.new(n,0)
dp[0]=1
for i in 0...n do
  tdp = Array.new(n,0)
  nd = h-a[i]
  tdp[nd] = ( tdp[nd] + dp[nd] ) % mod if nd >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd] * nd ) % mod if nd-1 >= 0 && nd < n
  tdp[nd] = ( tdp[nd] + dp[nd-1] ) % mod if nd-1 >= 0 && nd < n
  tdp[nd-1] = ( tdp[nd-1] + dp[nd-1] ) % mod if nd-1 >= 0
  dp = tdp
end
puts dp[0]