Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.

The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.

Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.

def binary_find(array, key)
    low = 0
    high = array.size - 1
    ret = 0
    while low <= high
        mid = low + high >> 1
        ret = mid if array[mid] >= key
        if array[mid] >= key then high = mid - 1
        else low = mid + 1
        end
    end
    ret
end
n, m = gets.split(' ').map { |i| i.to_i }
a = [0]
n.times do
    a.push a[-1] + gets.split(' ').inject { |mem, var|  mem = var.to_i * mem.to_i}
end
q = gets.split(' ').map { |i| i.to_i }
q.each do |qu|
    puts binary_find(a, qu)
end


There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \le m \le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \le n\le 100$$$).

For each testcase, print two lines with your answer.  In the first line print $$$m$$$ ($$$1\le m \le 1000$$$) — the number of operations you want to take.  In the second line print $$$m$$$ positive integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), where $$$a_j$$$ is the number of bag you chose on the $$$j$$$-th operation.

NoteIn the first case, adding $$$1$$$ candy to all bags except of the second one leads to the arrangement with $$$[2, 2]$$$ candies.In the second case, firstly you use first three operations to add $$$1+2+3=6$$$ candies in total to each bag except of the third one, which gives you $$$[7, 8, 3]$$$. Later, you add $$$4$$$ candies to second and third bag, so you have $$$[7, 12, 7]$$$, and $$$5$$$ candies to first and third bag  — and the result is $$$[12, 12, 12]$$$.

gets.to_i.times{
    n=gets.to_i
    p n-1
    t = []
    (n-1).times{|x|
        t << x + 2
    }
    puts t*' '
}

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  puts n
  puts (1..n).to_a.join ' '
end

testcases = gets.chomp.to_i
testcases.times do
  bags = gets.chomp.to_i
  j_bags = (1..bags).to_a
  puts j_bags.size
  puts j_bags.join(" ")
end

gets.to_i.times{
    n=gets.to_i
    p n-1
    t = []
    (n-1).times{|x|
        t << x + 1
    }
    puts t*' '
}

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  puts n
  puts (1..n).to_a.reverse.join ' '
end

testcases = gets.chomp.to_i

testcases.times do
  bags = gets.chomp.to_i
  total_moves = 0
  j_bags = []
  baggies = (1..bags).to_a
  while baggies.uniq.length > 1

    max = baggies.max
    max_bag = baggies.find_index { |x| x == max }

    j_bags << max_bag + 1
    baggies = baggies.each_with_index.map do |x, i|
      x += 1 unless i == max_bag
      x
    end
    total_moves += 1

  end
  puts total_moves
  puts j_bags.join(" ")

end

testcases = gets.chomp.to_i

testcases.times do
    bags = gets.chomp.to_i
    puts 1
    puts bags
end


Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows:   $$$a_1 = -1$$$  $$$a_2 = 2$$$  $$$a_3 = -3$$$  $$$a_4 = 4$$$  $$$a_5 = -5$$$  And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the descriptions of the queries.

Print $$$q$$$ lines, each containing one number — the answer to the query.

NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$.

q = gets.to_i

def f(x)
  ((-1)**(x%2))*x
end

q.times do
  quer = gets.chomp.split(" ").map(&:to_i)
  l = quer[0]
  r = quer[1]

  if (l%2==1 and r%2==0)
    puts (r-l+1)/2
  elsif (l%2==0 and r%2==1)
    puts -1*(r-l+1)/2
  elsif l%2==0 and r%2==0
    puts f(l)+(r-l)/2
  else
    puts f(r)+(r-l)/2
  end
end


You are given a program that consists of $$$n$$$ instructions. Initially a single variable $$$x$$$ is assigned to $$$0$$$. Afterwards, the instructions are of two types:   increase $$$x$$$ by $$$1$$$;  decrease $$$x$$$ by $$$1$$$. You are given $$$m$$$ queries of the following format:   query $$$l$$$ $$$r$$$ — how many distinct values is $$$x$$$ assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the description of $$$t$$$ testcases follows. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of $$$n$$$ characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next $$$m$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the query. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$m$$$ integers — for each query $$$l$$$, $$$r$$$ print the number of distinct values variable $$$x$$$ is assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order.

NoteThe instructions that remain for each query of the first testcase are:   empty program — $$$x$$$ was only equal to $$$0$$$;  "-" — $$$x$$$ had values $$$0$$$ and $$$-1$$$;  "---+" — $$$x$$$ had values $$$0$$$, $$$-1$$$, $$$-2$$$, $$$-3$$$, $$$-2$$$ — there are $$$4$$$ distinct values among them;  "+--+--+" — the distinct values are $$$1$$$, $$$0$$$, $$$-1$$$, $$$-2$$$.

gets.to_i.times do
  n,m=gets.split.map(&:to_i)
  s=gets.chomp.chars
  b=[0]
  slu=[0]
  sld=[0]
  a=0
  s.each do |ss|
    if ss=="+"
      a+=1
    else
      a-=1
    end
    b << a
    if a>slu[-1]
      slu << a
    else
      slu << slu[-1]
    end
    if a<sld[-1]
      sld << a
    else
      sld << sld[-1]
    end
  end
  sru=[a]
  srd=[a]
  s.reverse.each do |ss|
    if ss=="-"
      a+=1
    else
      a-=1
    end
    if a>sru[-1]
      sru << a
    else
      sru << sru[-1]
    end
    if a<srd[-1]
      srd << a
    else
      srd << srd[-1]
    end
  end
  sru.reverse!
  srd.reverse!
  m.times do
    l,r=gets.split.map(&:to_i)
    x=[slu[l-1],sld[l-1],sru[r]+b[l-1]-b[r],srd[r]+b[l-1]-b[r]]
    puts x.max-x.min+1
  end
end


Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.

The first line contains an integer n (1 ≤ n ≤ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Print the single number — the number of the winning squares.

NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3

n = gets.to_i
ary = Array.new(n).map!{ Array.new(n, 0) }
for r in 0..n-1
  line = gets
  s = line.split(' ')
  for c in 0..n-1
    ary[r][c] = s[c].to_i
  end
end
cnt = 0
for r in 0..n-1
  for c in 0..n-1
    col = 0
    row = 0
    for i in 0..n-1
      col += ary[i][c]
    end
    for i in 0..n-1
      row += ary[r][i]
    end
    if col > row
      cnt += 1
    end
  end
end
puts cnt

n = gets.to_i
ary = Array.new(n).map!{ Array.new(n, 0) }
n.times { |r|
  s = gets.split.map(&:to_i)
  n.times { |c|
    ary[r][c] = s[c]
  }
}
cnt = 0
n.times { |r|
  n.times { |c|
    col = 0
    row = 0
    n.times { |i|
      col += ary[i][c]
    }
    n.times { |i|
      row += ary[r][i]
    }
    cnt += 1 if col > row
  }
}
p cnt

n = gets.to_i
ary = Array.new(n).map!{ Array.new(n, 0) }
n.times { |r|
  s = gets.split.map{ |e| e.to_i }
  n.times { |c|
    ary[r][c] = s[c]
  }
}
cnt = 0
n.times { |r|
  n.times { |c|
    col = 0
    row = 0
    n.times { |i|
      col += ary[i][c]
    }
    n.times { |i|
      row += ary[r][i]
    }
    if col > row; cnt += 1; end;
  }
}
p cnt

def winning?(rowpos, colpos, elem, game)

	# check row sum
	rowsum = 0
	$n.times do |i|
		rowsum += game[rowpos][i].to_i
	end

	# check col sum
	colsum = 0
	$n.times do |i|
		colsum += game[i][colpos].to_i
	end

	colsum > rowsum
end

$n = STDIN.gets.chomp.to_i
game = []
$n.times do |i|
	game << STDIN.gets.chomp.split(' ').map{|ch| ch.to_i}
end

count = 0
rowpos = 0
game.each do |row|
	colpos = 0
	row.each do |elem|
		count += 1 if winning?(rowpos, colpos, elem, game)
		colpos += 1
	end
	rowpos += 1
end

puts count

n = gets.to_i
board = []
sumg = []
sumv = Array.new(n){|i| i = 0}
n.times do |i|
    s = gets.split.map{|i| i.to_i}
    sum = 0
    s.map{|i| sum +=i}
    sumg << sum
    n.times do |j|
        sumv[j] += s[j]
    end
end
res = 0
n.times do |i|
    n.times do |j|
        if sumg[i] < sumv[j] then
            res += 1
        end
    end
end

puts res

n = gets.to_i
a = Array.new(n){gets.split.map &:to_i}
c = 0
n.times{|i|
    n.times{|j|
        x, y = 0, 0
        n.times{|k|
            x += a[i][k]
            y += a[k][j]
        }
        c += 1 if x < y
    }
}
p c

n = gets.to_i
map = []
n.times do
        map << gets.split.map(&:to_i)
end
ans = 0
n.times do |x|
        n.times do |y|
                s1, s2 = 0, 0
                n.times do |i|
                        s1+=map[i][x]
                        s2+=map[y][i]
                end
                ans += 1 if s1>s2
        end
end
p ans

n = gets.chomp.to_i

field = []
n.times do
  field << gets.chomp.split(" ").map{|e| e.to_i}
end

win = 0

field.each_with_index do |column, col_no|
  column_sum = column.inject(0){|sum, i| sum += i}

  column.each_with_index do |e, row_no|
    row_sum = 0
    0.upto(field.length - 1) do |a|
      row_sum += field[a][row_no]
    end

    if row_sum > column_sum
      win += 1
    end
  end
end

puts win

def win? i, j
  $array[i].inject(:+) < $array.transpose[j].inject(:+)
end
ind = (0...gets.to_i).to_a
$array = readlines.map(&:split).each { |a| a.map!(&:to_i) }
puts ind.product(ind).count { |i, j| win? i, j }

n = gets.to_i
row_sum = []
col_sum = Array.new(n) { 0 }
n.times do
	sum = 0
	gets.split("\s").map { |x| x.to_i}.each_with_index do |x, i|
		col_sum[i] += x
		sum += x
	end
	row_sum << sum
end

cells = 0
j = 0
col_sum.sort!
row_sum.sort.each_with_index do |r, i|
	while j < n
		if r < col_sum[j]
			break
		else
			j += 1
			cells += i
		end
	end
end
cells += n * (n - j)
puts cells

n=gets.chomp.to_i
sumcolumns=Array.new(n,0)
sumrows=Array.new(n,0)
for i in 0..(n-1)
 temp= gets.chomp.split.collect{|a| a.to_i}
 sumrows[i]=temp.reduce(:+)
 temp.each_index{|a| sumcolumns[a]=sumcolumns[a]+temp[a]}
end
count=0
sumcolumns.each{|a|count=count+sumrows.count{|b| a>b }}
print count

n = gets.to_i
nss = n.times.map{gets.split.map(&:to_i)}

answer = 0.upto(n-1).map do |i|
  0.upto(n-1).count do |j|
    nss[i].reduce(:+) < nss.map{|row| row[j]}.reduce(:+)
  end
end.reduce(:+)

p answer

public

def solve(matrix)
  lines = {}
  cols = {}

  matrix.each_with_index do |x,i|
    lines[i] = x.inject(0){|z,s| s + z}
  end

  transpose(matrix).each_with_index do |x,i|
    cols[i] = x.inject(0){|z,s| s + z}
  end

  size = matrix[0].count
  win = 0
  (0...size).each do |i|
      (0...size).each do |j|
        win += 1if cols[i] > lines[j]
      end
  end

  win
end

def transpose(matrix)
  size = matrix[0].count
  transponent = []

  (0...size).each do |i|
      transponent[i] = [1]*size
  end

  (0...size).each do |i|
      (0...size).each do |j|
        transponent[i][j] = matrix[j][i]
      end
  end
  transponent
end

def read(input)
  input.split("\n")
end

def plow(list)
  list.collect{|y| y.split(" ").collect{|x| x.to_i}}[1..-1]
end

if __FILE__ == $PROGRAM_NAME
  print solve(plow(read(STDIN.read)))
end

n = gets.chomp.to_i
squares = Array.new(n) { gets.split.collect{|x| x.to_i} }

winning = 0
(0..n-1).each{|i|
  row_sum = 0
  squares[i].collect{|x| row_sum += x}
  (0..n-1).each{|j|
    col_sum = 0
    squares.each{|s|
      col_sum += s[j]
    }
    winning += 1 if col_sum > row_sum
  }
}

puts winning

n=gets.to_i
a=[]
0.upto(n-1) do |i|
  a[i]=gets.chomp.scan(/\w+/)
end
for i in 0..n-1 do
  for j in 0..n-1 do
    a[i][j]=a[i][j].to_i
  end
end
b=[]
for i in 0..n-1 do
  b[i]=0
  for j in 0..n-1 do
    b[i]+=a[i][j]
  end
end
c=[]
for j in 0..n-1 do
  c[j]=0
  for i in 0..n-1 do
    c[j]+=a[i][j]
  end
end
k=0
for i in 0..n-1 do
  for j in 0..n-1 do
    if (b[i]<c[j]) then k+=1 end
  end
end
puts k

n = gets.to_i
board = []
for i in 0..(n-1)
	board[i] = []
	line = gets.split
	for j in 0 .. (n-1)
		board[i] << line[j].to_i
	end
end

row = []
col = []
for i in 0..n-1
	rowSum = 0
	colSum = 0
	for j in 0..n-1
		rowSum += board[i][j]
		colSum += board[j][i]
	end
	row[i] = rowSum
	col[i] = colSum
end

count = 0
for i in 0..n-1
	for j in 0..n-1
		if(col[i] > row[j])
			count += 1
		end
	end
end

puts count

n = gets.chomp.to_i
b = []
row_sums = []
col_sums = []
for i in 0...n
  b[i] = gets.chomp.split.map { |x| x.to_i }
  row_sums[i] = b[i].inject(:+)
  for j in 0...n
    col_sums[j] = (col_sums[j] || 0) + b[i][j]
  end
end

count = 0
for i in 0...n
  for j in 0...n
    count += 1 if col_sums[i] > row_sums[j]
  end
end
puts count

# Codeforces Round #110
# Problem A -- Game Outcome
a = []
n = gets.to_i
n.times { a << gets.split.map(&:to_i) }
rows = (columns = [0] * n).dup
(0...n).each do |i|
    (0...n).each do |j|
        rows[i] += a[i][j]
        columns[j] += a[i][j]
    end
end
puts rows.product(columns).select {|x, y| x < y }.size

board = Array.new(gets.to_i) { gets.split.map(&:to_i) }

rows_sum = board.map {|row| row.reduce(:+) }
cols_sum = board.transpose.map {|col| col.reduce(:+) }

count = 0
rows_sum.each do |rs|
  cols_sum.each do |cs|
    if rs < cs
	  count += 1
	end
  end
end

puts count

n = gets.to_i
board = Array.new
rowSums = Array.new
n.times do
  row = gets.split(" ")
  row = row.map do |e|
    e.to_i
  end
  rowSums.push(row.inject(:+))
  board.push(row)
end

colSums = Array.new

for col in 0...n
  colSum = 0
  for row in 0...n
    colSum += board[row][col]
  end
  colSums[col] = colSum
end

total = 0
for i in 0...n
  for j in 0...n
    if (colSums[j] > rowSums[i])
      total += 1
    end
  end
end

puts total

n = gets.to_i
right = Array.new(n) { 0 }
down = Array.new(n) { 0 }

n.times do |i|
  gets.split.each_with_index do |element, index|
    a =element.to_i
    right[i] = right[i] + a
    down[index] = down[index] + a
  end
end
counter = 0
right.sort!
down.sort!
down.each do |i|
  plus = right.find_index { |j| j>=i }
  if plus
    counter = counter + plus
  else
    counter = counter + right.size
  end
end
p counter

def winning?(rowpos, colpos, elem, game)

	# check row sum
	rowsum = 0
	$n.times do |i|
		rowsum += game[rowpos][i].to_i
	end

	# check col sum
	colsum = 0
	$n.times do |i|
		colsum += game[i][colpos].to_i
	end

	colsum > rowsum
end

$n = STDIN.gets.chomp.to_i
game = []
$n.times do |i|
	game << STDIN.gets.chomp.split(' ').map{|ch| ch.to_i}
end

res = 0
rowpos = 0
game.each do |row|
	colpos = 0
	row.each do |elem|
		res = elem if winning?(rowpos, colpos, elem, game)
		colpos += 1
	end
	rowpos += 1
end

puts res

n = gets.to_i
row_sum = []
col_sum = Array.new(n) { 0 }
n.times do
	sum = 0
	gets.split("\s").map { |x| x.to_i}.each_with_index do |x, i|
		col_sum[i] += x
		sum += x
	end
	row_sum << sum
end

cells = 0
j = 0
col_sum.sort!
row_sum.sort.each_with_index do |r, i|
	while j < n
		if r < col_sum[j]
			break
		else
			j += 1
			cells += i
		end
	end
end

puts cells

n = gets.chomp.to_i
b = []
row_sums = []
col_sums = []
for i in 0...n
  b[i] = gets.chomp.split.map { |x| x.to_i }
  row_sums[i] = b[i].inject(:+)
  for j in 0...n
    col_sums[j] = (col_sums[j] || 0) + b[i][j]
  end
end

count = 0
for i in 0...n
  for j in 0...n
    count += 1 if row_sums[i] > col_sums[j]
  end
end
puts count

n = gets.to_i
right = Array.new(n){0}
down = Array.new(n){0}

n.times do |i|
  gets.split.each_with_index do |element,index|
    a =element.to_i
    right[i] = right[i] + a
    down[index] = down[index] + a
  end
end
counter = 0
right.sort!
down.sort!
down.each do |i|
  plus = right.find_index{|j| j>=i}
  counter = counter + plus unless plus.nil?
end
p counter


There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.

t = gets.to_i

(1).upto(t) do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)
  i = -1
  j = n
  turn = true
  x=0
  y=0
  z=0
  prev = 0
  cur = 0
  while(i+1<j) do
    prev = cur
    cur = 0
    if(turn)
      while(true)
        i+=1
        if(i==j)
          break
        end
        cur+=a[i]
        x+=a[i]
        if(cur>prev)
          break
        end
      end
    else
      while(true)
        j-=1
        if(i==j)
          break
        end
        cur+=a[j]
        y+=a[j]
        if(cur>prev)
          break
        end
      end
    end
    z+=1
    turn = !turn
  end
  puts "#{z} #{x} #{y}"
end

# Created by IntelliJ IDEA.
# User: gautam.roy
# Date: 5/10/20
# Time: 10:29 PM
# To change this template use File | Settings | File Templates.
t = gets.to_i
for i in 1..t do
  n = gets.to_i
  a = gets.split(' ').map { |s| s.to_i }
  atot = 0
  btot = 0
  moves = 0
  lind = 0
  rind = a.size - 1
  bsum = 0
  while lind <= rind
    # a moves
    asum = 0
    while lind <= rind && asum <= bsum
      asum = asum + a[lind]
      lind += 1
    end
    if asum != 0
      moves += 1
      atot += asum
    end
    # puts "lind #{lind} asum #{asum}"

    # b moves
    bsum = 0
    while lind <= rind && bsum <= asum
      bsum = bsum + a[rind]
      rind -= 1
    end
    if bsum != 0
      moves += 1
      btot += bsum
    end
    # puts "rind #{rind} bsum #{bsum}"
  end
  puts "#{moves} #{atot} #{btot}"
end

gets.to_i.times{
    n=gets.to_i
    a=gets.split.map &:to_i
    res=0, 0, 0
    s=t=0
    while a.size>0
        s=0
        s+=a.shift while a.size>0 and s<=t
        res[1]+=s
        res[0]+=1

        break if a.empty?

        t=0
        t+=a.pop while a.size>0 and t<=s
        res[2]+=t
        res[0]+=1
    end

    puts res*' '
}

# coding: utf-8

t = gets.to_i
t.times {
    n = gets.to_i
    moves, remains, alice, bob, last_eaten = 0, 0, 0, 0, 0

    a = gets.split.map { |i|
        i = i.to_i
        remains += i
        i
    }
    turn = :alice
    while !a.empty?
        if remains > last_eaten
            tmp = 0
            while tmp <= last_eaten
                tmp += a.shift if turn == :alice
                tmp += a.pop if turn == :bob
            end

            moves += 1
            remains -= tmp
            last_eaten = tmp
            alice += tmp if turn == :alice
            bob += tmp if turn == :bob

            if turn == :alice
                turn = :bob
            else
                turn = :alice
            end
        else
            break
        end
    end

    # clean-up
    if turn == :alice
        alice += remains
    else
        bob += remains
    end

    # and if remains are available, add one move (cleanup eating)
    if remains > 0
        moves += 1
    end

    puts "#{moves} #{alice} #{bob}"
}

# coding: utf-8

t = gets.to_i
t.times {
    moves, remains, alice, bob, last_eaten = 0, 0, 0, 0, 0

    a = gets.split.map { |i|
        i = i.to_i
        remains += i
        i
    }
    turn = :alice
    while !a.empty?
        if remains > last_eaten
            tmp = 0
            while tmp <= last_eaten
                tmp += a.shift if turn == :alice
                tmp += a.pop if turn == :bob
            end

            moves += 1
            remains -= tmp
            last_eaten = tmp
            alice += tmp if turn == :alice
            bob += tmp if turn == :bob

            if turn == :alice
                turn = :bob
            else
                turn = :alice
            end
        else
            break
        end
    end

    # clean-up
    if turn == :alice
        alice += remains
    else
        bob += remains
    end

    # and if remains are available, add one move (cleanup eating)
    if remains > 0
        moves += 1
    end

    puts "#{moves} #{alice} #{bob}"
}


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.

Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

a, d = gets.split(' ').map { |e| e = e.to_f }
n = gets.to_i

def getCoord st, c, a
	ac = (a-c).round(4)
	c = c.round(4)

	case st
		when 0 then "#{c} 0"
		when 1 then "#{a} #{c}"
		when 2 then "#{a-c} #{a}"
		when 3 then "0 #{a - c}"
	end
end

state = 0
c = 0
cd = d

for i in 0...n
	m = (cd / a).floor
	state = (state + m) % 4
	c = cd - m * a
	cd = c + d

	puts getCoord state, c, a
end

eps = 1e-5
a,d = gets.chomp!.split.map { |e|  e.to_f}
n =gets.chomp!.to_i
cur_x=0.00
cur_y=0.00
pp=0.00

n.times {
	if cur_y <= eps
		pp = cur_x
	#	p 0
	elsif a-cur_x <= eps
		pp = a + cur_y
	#	p 1
	elsif a-cur_y <= eps
		pp = a*3 -cur_x
	#	p 2
	else
		pp = a*4 -cur_y
	#	p 3
	end
	pp +=d;
	t= (pp/a).floor
	# puts "asd   #{pp}  #{t}  #{pp}"
	pp -= 1.0*t*a;

	case t%4
	when 0
		cur_x=pp
		cur_y=0
	when 1
		cur_x=a
		cur_y=pp
	when 2
		cur_x=a-pp
		cur_y=a
	when 3
		cur_x=0
		cur_y=a-pp
	end

	printf("%.8f %.8f\n",cur_x,cur_y)
}


The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 105) — the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.

In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.

class MaskGuesser
  def initialize num_networks, ip_list
    raise Exception unless ip_list.kind_of?(Array)
    @num_networks = num_networks
    @ip_list = Array.new(ip_list.map {|ip| ip_to_bitmask(ip)})
  end

  def guess_mask
    mask = 0
    31.downto(1) do |i|
      mask += 2**i
      masked_ip_list = @ip_list.map {|ip| ip&mask}.uniq
      return bitmask_to_ip(mask) if masked_ip_list.length == @num_networks
    end
    return "-1"
  end

  def bitmask_to_ip bitmask
    filter = 255
    a = (bitmask & (filter << 24)) >> 24
    b = (bitmask & (filter << 16)) >> 16
    c = (bitmask & (filter << 8)) >> 8
    d = bitmask & filter
    return "#{a}.#{b}.#{c}.#{d}"
  end

  def ip_to_bitmask ip
    bit_segments = ip.split('.').map(&:to_i)
    raise Exception if bit_segments.length != 4
    bitmask = bit_segments[0] << 24 | bit_segments[1] << 16 | bit_segments[2] << 8 | bit_segments[3]
    #bitmask = (bit_segments[0] << 24) + (bit_segments[1] << 16) + (bit_segments[2] << 8) + bit_segments[3]
    return bitmask
  end
end

def main
  num_ip, num_networks = gets.split(/\s+/).map(&:to_i)
  ip_list = []
  num_ip.downto(1) do
    ip_list << gets
  end
  m = MaskGuesser.new(num_networks, ip_list)
  puts m.guess_mask
end

main

D = [2 ** 24, 2 ** 16, 2 ** 8, 1]

def from_ip(ip)
  ip.split('.').each_with_index.map{ |n, i| n.to_i * D[i] }.reduce(:+)
end

def to_ip(ip)
  4.times.map{ |i| (ip / D[i]).tap{ ip %= D[i] } }.join('.')
end

def mask(n)
  ('1' * n << '0' * (32 - n)).to_i(2)
end

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

ips = []

n.times{ ips << from_ip(gets) }
ips.sort!

32.times do |i|
  next if i == 0 || 2 ** i < k
  m = mask(i)
  net = -1
  c = 0
  ips.each do |ip|
    ip_net = ip & m
    unless ip_net == net
      net = ip_net
      c += 1
    end
  end

  if c == k
    puts to_ip(m)
    exit
  end

end

puts -1

at_exit do
  n,k = get_numbers_from_line[0..1]
  ips = []
  n.times do
    octets = gets.strip.split('.').map(&:to_i)
    ips << (0...4).reduce(0){|result,i| result + (octets[i] << (8*i)) }
  end

  ip_and = 1<<32 - 1
  ip_or = 0
  (0...n).each do |i|
    ip_and &= ips[i]
    ip_or |= ips[i]
  end
  ip_xor = ip_and ^ ip_or

  result_mask = '-1'
  mask = 0
  start_i = [Math.log(k,2).ceil - 1, 0].max
  (0...start_i).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask |= 1 << (octet*8 + bit)
  end

  i = start_i
  while i < 32
    octet = i/8
    bit = 7 - i%8
    absolute_bit = octet*8 + bit
    mask |= 1 << absolute_bit
    nets = ips.map{|ip| ip & mask }.uniq
    if nets.length == k
      result_mask = (1..4).map{|j| (mask & ((1<<j*8) - 1)) >> ((j-1)*8)}.join('.')
      break
    elsif nets.length > k
      break
    end

    while true
      i += 1
      break if i >= 32
      octet = i/8
      bit = 7 - i%8
      absolute_bit = octet*8 + bit
      mask |= 1 << absolute_bit
      break if (ip_xor & (1 << absolute_bit)) != 0
    end
  end

  puts result_mask
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

at_exit do
  n,k = get_numbers_from_line[0..1]
  ips = []
  n.times do
    octets = gets.strip.split('.').map(&:to_i)
    ips << (0...4).reduce(0){|result,i| result + (octets[i] << (8*i)) }
  end

  ip_and = 1<<32 - 1
  ip_or = 0
  (0...n).each do |i|
    ip_and &= ips[i]
    ip_or |= ips[i]
  end
  ip_xor = ip_and ^ ip_or

  result_mask = '-1'
  start_i = Math.log(k,2).ceil - 1
  mask = 0
  (0...start_i).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask |= 1 << (octet*8 + bit)
  end

  i = start_i
  while i < 32
    octet = i/8
    bit = 7 - i%8
    absolute_bit = octet*8 + bit
    mask |= 1 << absolute_bit
    nets = ips.map{|ip| ip & mask }.uniq
    if nets.length == k
      result_mask = (1..4).map{|j| (mask & ((1<<j*8) - 1)) >> ((j-1)*8)}.join('.')
      break
    elsif nets.length > k
      break
    end

    while i < 32
      i += 1
      octet = i/8
      bit = 7 - i%8
      absolute_bit = octet*8 + bit
      mask |= 1 << absolute_bit
      break if (ip_xor & (1 << absolute_bit)) != 0
    end
  end

  puts result_mask
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

at_exit do
  n,k = get_numbers_from_line[0..1]
  ips = []
  n.times do
    ips << gets.strip.split('.').map(&:to_i)
  end

  result_mask = '-1'
  start_i = Math.log(k,2).floor
  mask = [0]*4
  (0...start_i).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask[octet] |= 1 << bit
  end

  (start_i...32).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask[octet] |= 1 << bit
    nets = ips.map{|ip| get_net_ip(ip, mask) }.uniq
    if nets.length == k
      result_mask = mask.join('.')
      break
    elsif nets.length > k
      break
    end
  end

  puts result_mask
end

def get_net_ip(ip, mask)
  (0...4).map{|i| ip[i] & mask[i] }
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

at_exit do
  n,k = get_numbers_from_line[0..1]
  ips = []
  n.times do
    ips << gets.strip.split('.').map(&:to_i)
  end

  result_mask = '-1'
  start_i = Math.log(k,2).ceil
  mask = [0]*4
  (0...start_i).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask[octet] |= 1 << bit
  end
  (start_i...32).each do |i|
    octet = i/8
    bit = 7 - i%8
    mask[octet] |= 1 << bit
    nets = ips.map{|ip| get_net_ip(ip, mask) }.uniq
    if nets.length == k
      result_mask = mask.join('.')
      break
    elsif nets.length > k
      break
    end
  end

  puts result_mask
end

def get_net_ip(ip, mask)
  (0...4).map{|i| ip[i] & mask[i] }
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end


Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can "see an elephant".

The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.

Print the number of segments in the bears' wall where Horace can "see an elephant".

NoteThe picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.

#!/usr/bin/env ruby

def pow(a, b, m)
  return (b == 0 ? 1 : pow(a * a % m, b / 2, m) * (b % 2 == 0 ? 1 : a)) % m
end

P = 1000000007
M = 2345678917
n, m = gets.split.map(&:to_i)

if m == 1
  puts n
  exit
end

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

da = a.drop(1).zip(a[0..-2]).map{|a, b| a - b}
hb = b.drop(1).zip(b[0..-2]).map{|a, b| a - b}.inject{|a, x| (a * P + x) % M}

n -= 1
m -= 1
MP = pow(P, m, M)

ans = 0
ha = 0
da.each_with_index do |x, i|
  ha = (ha * P + x) % M
  ha = (ha - da[i - m] * MP) % M if i >= m
  ans += 1 if i >= m - 1 && ha == hb
end

puts ans

#!/usr/bin/env ruby

def pow(a, b, m)
  return (b == 0 ? 1 : pow(a * a % m, b / 2, m) * (b % 2 == 0 ? 1 : a)) % m
end

P = 1000000007
M = 2345678917
n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)

da = a.drop(1).zip(a[0..-2]).map{|a, b| a - b}
hb = b.drop(1).zip(b[0..-2]).map{|a, b| a - b}.inject{|a, x| (a * P + x) % M}

n -= 1
m -= 1
MP = pow(P, m, M)

ans = 0
ha = 0
da.each_with_index do |x, i|
  ha = (ha * P + x) % M
  ha = (ha - da[i - m] * MP) % M if i >= m
  ans += 1 if i >= m - 1 && ha == hb
end

puts ans


Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following:   Set $$$d$$$ to be the maximum value of your array.  For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!

Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) – the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ – the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.

NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$.

t = gets.chomp.to_i
t.times {
  nk = gets.chomp.split(' ').map(&:to_i)
  n = nk[0]
  k = nk[1]
  arr = gets.chomp.split(' ').map(&:to_i)
  max = arr.max
  arr.map! { |ele| max - ele }
  max = arr.max
  if k % 2 == 0
    arr.map! { |ele| max - ele }
  end
  arr.each {|ele| print "%d " % ele }
  print "\n"
}

t = gets.chomp.to_i
t.times {
  nk = gets.chomp.split(' ').map(&:to_i)
  n = nk[0]
  k = nk[1]
  arr = gets.chomp.split(' ').map(&:to_i)
  max = arr.max
  arr.map! { |ele| max - ele }
  max = arr.max
  if k % 2 == 0
    arr.map! { |ele| max - ele }
  end
  arr.each {|ele| print "%d " % ele }
  # print "\n"
}

def get_max(a)
	res = a[0]
	for i in 1..(a.length-1)
		if a[i] > res
			res = a[i]
		end
	end
	res
end

def flip_array!(a)
	m = get_max(a)
	for i in 0..(a.length-1)
		a[i] = m - a[i]
	end
	nil
end

t = gets.chomp.to_i
for tc in 1..t
	a = gets.split
	n = a[0].to_i
	k = a[1].to_i
	a = gets.split
	for i in 0..(n-1)
		a[i] = a[i].to_i
	end
	flip_array!(a)

	if (k%2 == 0)
		flip_array!(a)
	end
	for i in 0..(n-1)
		print(a[i])
		print(" ")
	end
	print("\n")
end

t = gets.chomp.to_i
t.times {
  nk = gets.chomp.split(' ').map(&:to_i)
  n = nk[0]
  k = nk[1]
  arr = gets.chomp.split(' ').map(&:to_i)
  max = arr.max
  arr.map! { |ele| max - ele }
  max = arr.max
  if k % 2 == 0
    arr.map! { |ele| max - ele }
  end
  p arr.join(' ')
}


In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?

The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \leq a, b \leq 10^{9}$$$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.

In the first line print a single integer $$$n$$$ ($$$0 \leq n \leq a$$$) — the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \leq m \leq b$$$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \ldots, q_m$$$ ($$$1 \leq q_i \leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.

NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total.

a,b = gets.split.map(&:to_i)
t = Math.sqrt((a+b)*2).floor
for i in t..t+3
  if (a+b)*2 < i*(i+1)
    m = i-1
    break
  end
end

c,d = [],[]
m.downto(1) do |i|
  if a >= i
    a -= i
    c.push(i)
  else
    b -= i
    d.push(i)
  end
end

puts c.size,c.join(" "),d.size,d.join(" ")


Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that  $$$a$$$ has at least $$$4$$$ divisors;  difference between any two divisors of $$$a$$$ is at least $$$d$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3000$$$) — the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \leq d \leq 10000$$$).

For each test case print one integer $$$a$$$ — the answer for this test case.

NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$.

require "prime"
a=[1]+Prime.each(100000).to_a
az=a.size
gets.to_i.times do
  d=gets.to_i
  l=0
  r=az-1
  while r-l>1
    m=(l+r)/2
    if a[m]<=d
      l=m
    else
      r=m
    end
  end
  x=a[r]
  l=0
  r=az-1
  while r-l>1
    m=(l+r)/2
    if a[m]<x+d
      l=m
    else
      r=m
    end
  end
  y=a[r]
  puts x*y
end

gets.to_i.times do
  d=gets.to_i
  puts 200250077
end


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — the initial sum in rubles Andrew has.  The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$) — the price of one dollar in rubles.  The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$) — the price of one euro in rubles.

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.

n = gets.to_i
d = gets.to_i
e = gets.to_i
eu = e*5

min = n
(n/d+1).times do |i|
  x = n - d*i
  break if x<0

  x -= x/eu * eu
  min = x if min>x

  break if min==0
end

puts min

n = gets.to_i
d = gets.to_i
e = gets.to_i

ans = n

(0..(n/d)).each do |dn|
  ans = [ans, (n - (d*dn)) % (e*5)].min
end

puts ans

n = gets.to_i
d = gets.to_i
e = gets.to_i

ans = 10 ** 20
tmp = n % d % (e*5)
tmp2 = n % (e*5) % d
ans = [ans, tmp, tmp2].min
puts ans

n = gets.to_i
d = gets.to_i
e = gets.to_i

ans = n

tmp = n % d % (e*5)
tmp2 = n % (e*5) % d
ans = [ans, tmp, tmp2].min
puts ans


Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once.  Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains $$$3$$$ integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$).

For each test case print "YES" (without quotes) if Polycarp can choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$ to make $$$[a, b, c]$$$ be an arithmetic progression. Print "NO" (without quotes) otherwise. You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

YES
YES
YES
YES
NO
YES
NO
YES
YES
NO
YES

NoteIn the first and second test cases, you can choose the number $$$m=4$$$ and multiply the second number ($$$b=5$$$) by $$$4$$$.In the first test case the resulting sequence will be $$$[10, 20, 30]$$$. This is an AP with a difference $$$d=10$$$.In the second test case the resulting sequence will be $$$[30, 20, 10]$$$. This is an AP with a difference $$$d=-10$$$.In the third test case, you can choose $$$m=1$$$ and multiply any number by $$$1$$$. The resulting sequence will be $$$[1, 2, 3]$$$. This is an AP with a difference $$$d=1$$$.In the fourth test case, you can choose $$$m=9$$$ and multiply the first number ($$$a=1$$$) by $$$9$$$. The resulting sequence will be $$$[9, 6, 3]$$$. This is an AP with a difference $$$d=-3$$$.In the fifth test case, it is impossible to make an AP.

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    a, b, c = inp.split(' ').map(&:to_i)

    if a - b  == b - c
        puts "YES"
    else
        if (2 * b - c) % a == 0 && (2 * b - c) / a > 0
            puts "YES"
        elsif (a + c) % (2 * b) == 0 && (a + c) / (2 * b) > 0
            puts "YES"
        elsif (2 * b - a) % c == 0 && (2 * b - a) / c > 0
            puts "YES"
        else
            puts "NO"
        end
    end
end

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

  # Is it `a`?
  d = c - b
  aa = b - d
  if aa % a == 0 && aa / a > 0
    puts "YES"
    next
  end

  # `b`?
  d = c - a
  if d % 2 == 0
    d /= 2
    bb = c - d
    if bb % b == 0 && bb / b > 0
      puts "YES"
      next
    end
  end

  # `c`?
  d = b - a
  cc = b + d
  if cc % c == 0 && cc / c > 0
    puts "YES"
    next
  end

  puts "NO"
end

#!/usr/bin/ruby
input = ARGF.read.each_line(chomp: true).to_a
header = input.shift
input.each do |line|
  z = line.split.map(&:to_i)
  puts ((2*z[1] -z[2] > 0 and (2*z[1] - z[2]) % z[0] == 0) or
    ((z[0] + z[2]) % (2*z[1]) == 0) or
    (2*z[1] -z[0] > 0 and (2*z[1] - z[0]) % z[2] == 0)) ? "YES" : "NO"
end

t = readline.strip.to_i

t.times do
  a, b, c = readline.strip.split(/\s+/).map(&:to_i)
  if a == b && b == c
    puts 'YES'
    next
  end

  # case 1 |a| b c
  d = c - b
  if ((b - d) % a == 0) && ((c - 2*d) % a == 0)
    m = (b-d) / a
    if m > 0
      puts 'YES'
      next
    end
  end

  # case a |b| c
  d = c - a
  if d % 2 == 0
    d /= 2
    if ((a+d) % b == 0) && ((c-d) % b == 0)
      m = (a+d) / b
      if m > 0
        puts 'YES'
        next
      end
    end
  end

  # case a b |c|
  d = b - a
  if ((b+d) % c == 0) && ((a+2*d) % c == 0)
    m = (b + d) / c
    if m > 0
      puts 'YES'
      next
    end
  end

  puts 'NO'
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    a, b, c = inp.split(' ').map(&:to_i)

    min = [a,c].min
    max = [a,c].max

    if (a > c || a < c) && max - min > 1
        puts "YES"
    else
        if a == b && b == c
            puts "YES"
        else
            if (a + c) * b == b * 2
                puts "YES"
            elsif (b == c && a * b == b) || (a == b && b * c == b)
                puts "YES"
            else
                puts "NO"
            end
        end
    end
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    a, b, c = inp.split(' ').map(&:to_i)

    if a > c
        a, c = c, a
    end

    # pp "#{a}, #{b}, #{c}"
    x = Hash[[a,b,c].tally.to_a.reverse]
    if x[2].to_i * x[1].to_i == x[2].to_i
        puts "YES"
        next
    end
    if (a == b && b == c) || (a == 1 && c == 1)
        puts "YES"
        next
    end
    if c - a < 2
        puts "NO"
        next
    end
    if a + b != c && a + (c - a) != c
        puts "NO"
        next
    end

    puts "YES"
end

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

  # Is it `a`?
  d = c - b
  aa = b - d
  if aa % a == 0 && aa / a > 0
    puts "YES"
    next
  end

  # `b`?
  d = c - a
  if d % 2 == 0
    bb = c - d
    if bb % b == 0 && bb / b > 0
      puts "YES"
      next
    end
  end

  # `c`?
  d = b - a
  cc = b + d
  if cc % c == 0 && cc / c > 0
    puts "YES"
    next
  end

  puts "NO"
end


Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of throws of the first team. Then follow n integer numbers — the distances of throws ai (1 ≤ ai ≤ 2·109).  Then follows number m (1 ≤ m ≤ 2·105) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of bi (1 ≤ bi ≤ 2·109).

Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.

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

class Score
  def self.start
    self.new
  end

  def initialize
    aggregate
  end

  def aggregate
    n = gets.chomp.to_i
    @f = Team.new(gets.chomp.split.map(&:to_i))
    m = gets.chomp.to_i
    @s = Team.new(gets.chomp.split.map(&:to_i))
  end

  def result
    f_score = @f.score
    s_score = @s.score
    f = @f.score_l
    s = @s.score_l
    n = f.length
    m = s.length

    ans = -1000000
    diff_score = f_score - s_score
    if ans < f_score - s_score
      ans = diff_score
      ans_f = f_score
      ans_s = s_score
    end

    j = 0
    @s.score_l.length.times do |i|
      s_score -= 1
      while j < n and f[j] <= s[i]
        f_score -= 1
        j += 1
      end
      diff_score = f_score - s_score
      if ans < diff_score
        ans = diff_score
        ans_f = f_score
        ans_s = s_score
      end
    end
    return "#{ans_f}:#{ans_s}"
  end
end

class Team
  attr_reader :score_l, :score
  def initialize(score_l)
    @score_l = score_l.sort
    @score = @score_l.length * 3
  end
end

s = Score.start
puts s.result

class Info
  attr_accessor :dist
  attr_accessor :team

  def initialize (d, t)
    @dist = d
    @team = t
  end
end

gets
first = gets.split(' ').map do |x|
  Info.new(x.to_i, 1)
end

gets
second = gets.split(' ').map do |x|
  Info.new(x.to_i, 2)
end

res = first + second
res.sort_by! { |x| -x.dist }

d = res.max_by { |x| x.dist }.dist + 1

two_points_first, three_points_first  = first.length, 0
two_points_second, three_points_second  = second.length, 0

max_first = two_points_first * 2 + three_points_first * 3
max_second = two_points_second * 2 + three_points_second * 3
diff = max_first - max_second

points = first.map { |x| x.dist } + second.map { |x| x.dist }
points = points.uniq.sort.reverse

current = 0
for i in points
  while current < res.length && res[current].dist >= i do
    if res[current].team == 1
      two_points_first -= 1
      three_points_first += 1
    else
      two_points_second -= 1
      three_points_second += 1
    end

    current += 1
  end

  local_first = two_points_first * 2 + three_points_first * 3
  local_second = two_points_second * 2 + three_points_second * 3

  loc_diff = local_first - local_second

  if loc_diff >= diff
    diff = loc_diff
    max_first, max_second = local_first, local_second
  end

  break if current == res.length
end

puts "#{max_first}:#{max_second}"

class Info
  attr_accessor :dist
  attr_accessor :team

  def initialize (d, t)
    @dist = d
    @team = t
  end
end

gets
first = gets.split(' ').map do |x|
  Info.new(x.to_i, 1)
end

gets
second = gets.split(' ').map do |x|
  Info.new(x.to_i, 2)
end

res = first + second
res.sort_by! { |x| -x.dist }

d = res.max_by { |x| x.dist }.dist + 1

two_points_first, three_points_first  = first.length, 0
two_points_second, three_points_second  = second.length, 0

max_first = two_points_first * 2 + three_points_first * 3
max_second = two_points_second * 2 + three_points_second * 3
diff = max_first - max_second

current = 0
d.downto(1) do |i|
  while current < res.length && res[current].dist >= i do
    if res[current].team == 1
      two_points_first -= 1
      three_points_first += 1
    else
      two_points_second -= 1
      three_points_second += 1
    end

    local_first = two_points_first * 2 + three_points_first * 3
    local_second = two_points_second * 2 + three_points_second * 3

    loc_diff = local_first - local_second

    if loc_diff >= diff
      diff = loc_diff
      max_first, max_second = local_first, local_second
    end

    current += 1
  end

  break if current == res.length
end

puts "#{max_first}:#{max_second}"

class Info
  attr_accessor :dist
  attr_accessor :team

  def initialize (d, t)
    @dist = d
    @team = t
  end
end

gets
first = gets.split(' ').map do |x|
  Info.new(x.to_i, 1)
end

gets
second = gets.split(' ').map do |x|
  Info.new(x.to_i, 2)
end

res = first + second
res.sort_by! { |x| -x.dist }

d = res.max_by { |x| x.dist }.dist + 1

two_points_first, three_points_first  = first.length, 0
two_points_second, three_points_second  = second.length, 0

max_first = two_points_first * 2 + three_points_first * 3
max_second = two_points_second * 2 + three_points_second * 3
diff = max_first - max_second

current = 0
d.downto(1) do |i|
  while current < res.length && res[current].dist >= i do
    if res[current].team == 1
      two_points_first -= 1
      three_points_first += 1
    else
      two_points_second -= 1
      three_points_second += 1
    end

    local_first = two_points_first * 2 + three_points_first * 3
    local_second = two_points_second * 2 + three_points_second * 3

    loc_diff = local_first - local_second

    if loc_diff > diff
      diff = loc_diff
      max_first, max_second = local_first, local_second
    end

    current += 1
  end

  break if current == res.length
end

puts "#{max_first}:#{max_second}"


Once upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once.DravDe dreamt about managing a successful farm. He dreamt that every day one animal came to him and asked him to let it settle there. However, DravDe, being unimaginably kind, could send the animal away and it went, rejected. There were exactly n days in DravDe’s dream and the animal that came on the i-th day, ate exactly ci tons of food daily starting from day i. But if one day the animal could not get the food it needed, it got really sad. At the very beginning of the dream there were exactly X tons of food on the farm.DravDe woke up terrified...When he retold the dream to you, he couldn’t remember how many animals were on the farm by the end of the n-th day any more, but he did remember that nobody got sad (as it was a happy farm) and that there was the maximum possible amount of the animals. That’s the number he wants you to find out. It should be noticed that the animals arrived in the morning and DravDe only started to feed them in the afternoon, so that if an animal willing to join them is rejected, it can’t eat any farm food. But if the animal does join the farm, it eats daily from that day to the n-th.

The first input line contains integers n and X (1 ≤ n ≤ 100, 1 ≤ X ≤ 104) — amount of days in DravDe’s dream and the total amount of food (in tons) that was there initially. The second line contains integers ci (1 ≤ ci ≤ 300). Numbers in the second line are divided by a space.

Output the only number — the maximum possible amount of animals on the farm by the end of the n-th day given that the food was enough for everybody.

NoteNote to the first example: DravDe leaves the second and the third animal on the farm. The second animal will eat one ton of food on the second day and one ton on the third day. The third animal will eat one ton of food on the third day.

f = open("input.txt", "r")
n,x = f.gets.chomp.split(/ /).map!{|x|x.to_i}
ar = f.gets.chomp.split(/ /).map!{|x|x.to_i}
f.close
an = Array.new
for i in 0..n-1
	an.push(ar[i]*(n-i))
end
an.sort!
sum = 0
ret = 0
for i in 0..an.length-1
	if an[i] + sum <= x
		sum += an[i]
		ret += 1
	else
		break
	end
end
fw = open("output.txt", "w")
fw.puts ret
fw.close


Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \leq t \leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — the elements of the array $$$a$$$.

For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \leq k \leq 300$$$).  Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any.

$, = $\ = "\n"
gets.to_i.times do
    gets
    a = gets.split.map &:to_i
    if a.min < 0
        print "NO"
    else
        print "YES", a.max + 1, (0..a.max).to_a.join(" ")
    end
end

gets.to_i.times do
    gets
    a = gets.split.map &:to_i
    if a.min < 0
        puts "NO"
    else
        puts "YES"
        puts a.max + 1, (0..a.max).to_a.join(" ")
    end
end

gets.to_i.times do
    gets
    a = gets.split.map &:to_i
    if a.min < 0
        puts "NO"
    else
        puts "YES", a.max + 1, (0..a.max).to_a.join(" ")
    end
end

t = gets.to_i
t.times.each do
  n = gets.to_i
  as = gets.split.map(&:to_i)
  if as.min < 0
    puts 'no'
    next
  end

  g = as[0]
  as.each {|a| g = a.gcd(g) }
  max = as.max
  min = [as.min, g].min
  cnt = (max - min) / g + 1
  if cnt > 300
    puts 'no'
  else
    puts 'yes'
    puts cnt
    puts (min..max).step(g).map {|i| i }.join(' ')
  end
end


You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i<j$$$ and $$$a_i > a_j$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.

NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.

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

  return 0 if n == 1

  zeros = [0] * (n + 1)
  ones = [0] * (n + 1)
  n.times do |i|
    zeros[i + 1] = zeros[i]
    zeros[i + 1] += 1 if a[i] == 0
    ones[i + 1] = ones[i]
    ones[i + 1] += 1 if a[i] == 1
  end

  l_zero = a.index(0)
  l_one = a.index(1)
  r_zero = a.rindex(0)
  r_one = a.rindex(1)

  original = 0
  n.times do |i|
    original += zeros[n] - zeros[i] if a[i] == 1
  end
  ans = original

  tries = []
  tries << l_zero if l_zero
  tries << l_one if l_one
  tries << r_zero if r_zero
  tries << r_one if r_one

  tries.each do |x|
    a[x] ^= 1
    res = original
    if a[x] == 1
      res += zeros[n] - zeros[x + 1]
      res -= ones[x] - ones[0]
    else
      res += ones[x] - ones[0]
      res -= zeros[n] - zeros[x + 1]
    end
    ans = res if ans < res
    a[x] ^= 1
  end

  ans
}

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

gets.to_i.times{
    n=gets.to_i
    a=gets.split.map(&:to_i)
    b=a.clone
    c=a.clone
    if b.count(1)>0
        b[b.rindex(1)]=0
    end
    if c.count(0)>0
        c[c.index(0)]=1
    end
    counta=0
    countb=0
    countc=0
    ca=0
    cb=0
    cc=0
    n.times{|i|
        if a[i]==1
            ca+=1
        else
            counta+=ca
        end
        if b[i]==1
            cb+=1
        else
            countb+=cb
        end
        if c[i]==1
            cc+=1
        else
            countc+=cc
        end
    }
    print([counta,countb,countc].max,"\n")
}

gets.to_i.times{
    n = gets.to_i
    x = gets.split
    ones = (x.join('')).count('1')
    zeros = n-ones
    zeros1 = zeros
    initial = 0
    (n-1).times{|i|
        if x[i]=='1'
            initial+=zeros1
        else
            zeros1-=1
        end
    }
    y = x.reverse
    mx = 0
    n.times{|i|
        if x[i]=='0'
            a = -i + x[(i+1)..].count('0')
            mx = [mx,a].max
            break
        end
    }
    n.times{|i|
        if y[i]=='1'
            a = -i + y[(i+1)..].count('1')
            mx = [mx,a].max
            break
        end
    }
    p initial+mx
}

=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}
    ones=0
    etternull=0
    har=0
    sum=0
    ending =0
    prev=maks[0]
    for j in 0..(n-1)
        if (har==1)
            if maks[j]==1
                ones+=1
                ending =0
            else
                sum+=ones
                etternull+=1
                ending+=1
            end
        else
            if maks[j]==1
                ones+=1
                etternull-=1
                ending=0
            else
                sum+=ones
                har =1
                ending+=1
            end
        end
    end
    puts [sum, sum+etternull, sum+ones-ending-1].max
end

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

  return 1 if n == 1

  l_zero = a.index(0)
  l_one = a.index(1)
  r_zero = a.rindex(0)
  r_one = a.rindex(1)

  ans = n_inversions(a)

  tries = []
  tries << l_zero if l_zero
  tries << l_one if l_one
  tries << r_zero if r_zero
  tries << r_one if r_one

  tries.each do |x|
    a[x] ^= 1
    res = n_inversions(a)
    ans = res if ans < res
    a[x] ^= 1
  end

  ans
}

def n_inversions(seq)
  n = seq.size
  b = [0] * (n + 1)

  res = 0
  n.times do |i|
    s = 0
    j = seq[i] + 1
    while j > 0
      s += b[j]
      j -= (j & -j)
    end

    res += i - s

    j = seq[i] + 1
    while j < n
      b[j] += 1
      j += (j & -j)
    end
  end

  res
end

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

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

  return 0 if n == 1

  l_zero = a.index(0)
  l_one = a.index(1)
  r_zero = a.rindex(0)
  r_one = a.rindex(1)

  ans = n_inversions(a)

  tries = []
  tries << l_zero if l_zero
  tries << l_one if l_one
  tries << r_zero if r_zero
  tries << r_one if r_one

  tries.each do |x|
    a[x] ^= 1
    res = n_inversions(a)
    ans = res if ans < res
    a[x] ^= 1
  end

  ans
}

def n_inversions(seq)
  n = seq.size
  b = [0] * (n + 1)

  res = 0
  n.times do |i|
    s = 0
    j = seq[i] + 1
    while j > 0
      s += b[j]
      j -= (j & -j)
    end

    res += i - s

    j = seq[i] + 1
    while j < n
      b[j] += 1
      j += (j & -j)
    end
  end

  res
end

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

gets.to_i.times{
    n=gets.to_i
    s=gets.split.map(&:to_i)
    if s.count(1)>s.count(0)
        s[s.rindex(1)]=0
    elsif s.count(1)<s.count(0)
        s[s.index(0)]=1
    else
        s[s.rindex(1)]=0
    end
    count=0
    c=0
    s.size.times{|i|
        if s[i]==1
            c+=1
        else
            count+=c
        end
    }
    print(count,"\n")
}

gets.to_i.times{
    n = gets.to_i
    x = gets.split
    ones = (x.join('')).count('1')
    zeros = n-ones
    zeros1 = zeros
    initial = 0
    (n-1).times{|i|
        if x[i]=='1'
            initial+=zeros1
        else
            zeros1-=1
        end
    }
    y = []
    osf = 0
    n.times{|i|
        if x[i]=='1'
            y[i]=osf-zeros
            osf+=1
        else
            zeros-=1
            y[i]=zeros-osf
        end
    }
    p y.max+initial
}


You are given a sequence of positive integers a1, a2, ..., an. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements.For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.Determine the final sequence after you stop performing the operation.

The first line contains a single integer n (2 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.  In the second line print k integers — the sequence after you stop performing the operation.

NoteThe first example is described in the statements.In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].In the third example there are no two equal consecutive elements initially, so the sequence does not change.

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

cur1 = 1
cur = 0
ans = []

for i in c
  ans << i
  while ans.size > 1 and ans[-1] == ans[-2]
    cur = ans[-1]
    cur += 1
    ans.pop
    ans.pop
    ans << cur
  end
end

print "#{ans.size}"
print "\n"

for i in ans
  print "#{i} "
end

n = gets.to_i
a = gets.split.map(&:to_i)
b=[]
for x in a
	b<<x
	while b.size>1 and b[-1]==b[-2]
		b.pop
		b[-1]+=1
	end
end

print "#{b.size}"
print "\n"

for x in b
  print "#{x} "
end

# help from stackoverflow
n = gets.to_i
arr = gets.split.map(&:to_i)
i = 1
filled = 1
ans = []
tmp = arr[0]
ans << arr[0]
while i<n
    if filled == 0
        ans << arr[i]
        filled = filled +1
    elsif arr[i] == ans[-1]
        ans.pop
        ans << arr[i]+1
        while ans.length > 1 && ans[-1]==ans[-2]
            tmp = ans.pop
            ans.pop
            ans << tmp+1
            filled = filled -1
        end
    else
        ans << arr[i]
        filled= filled+1
    end

    i= i+1
end

puts filled

for i in (0..filled)
    print ans[i]
    print " "
end

n = gets.chomp.to_i
c = gets.split.map(&:to_i)
cur1 = 1
cur = 0
ans = []
for i in c
  ans << i
  while ans.size > 1 and ans[-1] == ans[-2]
    cur = ans[-1]
    ans.pop
    ans.pop
    cur += 1
    ans << cur
  end
end
print "#{ans.size}\n"
for i in ans
  print "#{i} "
end

n = gets.to_i
arr = gets.split(/[ \n]/);

st = Array.new(n) { |x|  }
len = 0
for x in arr
    x = x.to_i
    if (len != 0 && st[len - 1] == x)
        st[len - 1] += 1
    else
        st[len] = x
        len += 1
    end
    while (len > 1 && st[len - 2] == st[len - 1]) do
        len -= 1;
        st[len - 1] += 1
    end
end
puts len
for i in (0...len) do
    print "#{st[i]} ";
end

r=->{gets.split.map &:to_i}
n = r[]
n = n[0]
v = r[]
a = Array.new
n.times {|i|
    x = v[i]
    while a.length != 0 and a[a.length - 1] == x do
        a.pop()
        x = x + 1
    end
    a.push(x)
}
puts(a.length)
for x in a do
    print(x)
    print(" ")
end

n = gets.to_i
rs = gets.split.map &:to_i

got = []
i = 0
j = 0

while i < n do
  if got.size == 0 then
    got.push(rs[i])
  elsif rs[i] == got[j] then
    got[j] += 1
    while j > 0 && got[j] == got[j-1] do
      j -= 1
      got[j] += 1
    end
  else
    if j == got.size - 1 then
      got.push(rs[i])
      j += 1
    else
      j += 1
      got[j] = rs[i];
    end
  end

  i += 1
end

p j+1
print got[0..j].join(' ')

n = gets.to_i
rs = gets.split.map &:to_i

got = []
i = 0
j = 0;
while i < n do
  if got.size == 0 then
    got.push(rs[i])
  elsif rs[i] == got[j] then
    got[j] += 1
    while j > 0 && got[j] == got[j-1] do
      j -= 1
      got[j] += 1
    end
  else
    got.push(rs[i])
    j += 1
  end

  i += 1
end

p j+1
print got[0..j].join(' ')


You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following:   decrease the number on the clock by $$$1$$$, or  swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_1, s_2, \ldots, s_n \le 9$$$) — the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.

For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.

NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations.

=begin
Entrada: testcases, entero que indica la cantidad de dígitos,
        string de los dígitos
Salida: operaciones mínimas para que todos los dígitos sean 0
Movimientos permitidos: restar 1 a la cifra, cambiar el orden de una cifra
(adyacente y no adyacente)
=end

# Variables
testcases = 0
numberDigits = 0
digits = ""

# Constantes
condition = true
operationReduce = false
operationChange = true

# Paso 1: Pedir los testcases
testcases = Integer(gets.chomp)
movements = Array.new(testcases)

#Paso 2: Pedir la cantidad de dígitos
for i in (0..(testcases-1))
        numberDigits = Integer(gets.chomp)
        digits = gets.chomp
        movements[i] = 0
        count = 0
        digits.chars.each do |digit|
                count = count +1
                if Integer(digit)!=0
                        if count == numberDigits
                                movements[i] = movements[i] + digit.to_i
                        else
                                movements[i] = movements[i] + digit.to_i + 1
                        end
                end

        end
end
movements.each do |elements|
        puts elements
end

# require 'byebug'

gets.to_i.times do

  n = gets.to_i
  str = gets.strip

  ary = str.split("").map(&:to_i)
  ans = 0
  0.upto(n-1).each do |i|
    ans += ary[i]
    ans += 1 if ary[i] != 0 && i != n-1
  end

  puts ans

end

gets.to_i.times do |tt|
  n=gets.to_i
  s=gets.chomp.chars.map(&:to_i)
  puts s.inject(:+)+n-1-s[0,n-1].count(0)
end

gets.to_i.times do

n = gets.to_i
d = gets.chomp.chars.map!(&:to_i)

cnt = 0
d.reverse_each.with_index do |di, i|
  next if di == 0

  cnt += di
  cnt += 1 if i > 0
end

puts cnt

end


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

n = gets.to_i
x = (n-1).times.map{gets.to_i-1}

ha = Array.new(n, true)
ha[0] = false
x.each{|t| ha[t] = false}

cnt = Array.new(n, 0)
x.each.with_index{|t,i| cnt[t]+=1 if ha[i+1]}

puts (n.times.all?{|i| ha[i]||cnt[i]>2}) ? 'Yes' : 'No'


The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative. Vasya can change summer tires to winter tires and vice versa at the beginning of any day.Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.

The first line contains two positive integers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total. The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 ≤ ti ≤ 20) — the average air temperature in the i-th winter day.

Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.

NoteIn the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two. In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.

n, k = gets.split.map(&:to_i)
ts = gets.split.map { |i| i.to_i < 0 }
count = ts.count { |t| t }
if count > k
  puts -1
  exit
end
prev = nil
dts = []
ts.each_with_index do |t, i|
  if t && !prev
    prev = i
  elsif t && prev
    dts << i - prev - 1
    prev = i
  end
end
dts.sort!
sum = count
dif = 0
dts.each do |dt|
  if sum + dt <= k
    sum += dt
    dif += 1
  else
    break
  end
end
ans = (count - dif) * 2
last = ts.reverse.index { |t| t }
if last && last <= k - sum
  puts ans - 1
else
  puts ans
end

#!/bin/env ruby

class TireManager
  attr_accessor :weather_intervals, :minus_degree_days_count, :plus_degree_intervals, :reserve
  def getNumberOfCrisscrosses number_of_winter_days, tyre_life_in_days, weather_forecast
    @weather_intervals=weather_forecast.chunk {|degree| degree<0}.map {|x,y| [(x)?(:minus):(:plus),y.size]}
    @minus_degree_days_count = @weather_intervals.reduce(0) {|sum,interval| sum+=(interval[0]==:minus)?(interval[1]):0}
    case
      when @minus_degree_days_count > tyre_life_in_days
        -1
      when @minus_degree_days_count == 0
        0
       else
         @weather_intervals.shift if @weather_intervals[0][0]==:plus
         @reserve = tyre_life_in_days - @minus_degree_days_count
         @plus_degree_intervals = @weather_intervals[0...-1].select {|interv| interv[0]==:plus}.map {|x| x[1]}.sort
         @plus_degree_intervals = @plus_degree_intervals.drop_while {|x| (x<=@reserve)?(@reserve-=x;true):(false)}
         @plus_degree_intervals.size*2+1+((@weather_intervals[-1][0]==:plus&&@reserve<@weather_intervals[-1][1])?1:0)
    end
  end
end

if __FILE__ == $0
  number_of_winter_days,tyre_life_in_days = $stdin.readline.split.map(&:to_i)
  weather_forecast = $stdin.readline.rstrip.split.map(&:to_i)
  puts TireManager.new.getNumberOfCrisscrosses(number_of_winter_days, tyre_life_in_days, weather_forecast)
end


There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where  is bitwise xor operation (see notes for explanation).  Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

Print a single integer: the answer to the problem.

NoteIn the first sample there is only one pair of i = 1 and j = 2.  so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

n,x,*a=$<.read.split.map(&:to_i)
h=Hash.new(r=0)
a.each{|e|h[e]+=1}
h.each_key{|k|
	opp=k^x
	if opp==k
		r+=h[k]*(h[k]-1)/2
	elsif k<opp
		r+=h[k]*h[opp]
	end
}
p r

n, x=gets.split.map &:to_i
a=gets.split.map &:to_i

b=[]
a.each{|e|b[e]=b[e]?b[e]+1:1}
r=0
a.each{|e|
    r+=b[x^e] if b[x^e]
    r-=1 if x==0
}
p r/2

n,x,*a=$<.read.split.map(&:to_i)
h=Hash.new(r=0)
a.each{|e|h[e]+=1}
h.each_key{|k|
	opp=k^x
	if opp==k
		r+=h[k]*(h[k]+1)/2
	elsif k<opp
		r+=h[k]*h[opp]
	end
}
p r

n, x=gets.split.map &:to_i
a=gets.split.map &:to_i

b=[]
a.each{|e|b[e]=b[e]?b[e]+1:1}
r=0
a.each{|e|
    if b[e^x]
        r+=b[e^x]
        r-=1 if e==x
    end
}
p r/2


Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.

The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph. The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.

If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph. In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.

n,k = gets.chomp!.split.map {|e| e.to_i}

D = gets.chomp!.split.map {|e| [e.to_i,0]}
flag = 0
n.times { |i|
    D[i][1]=i+1
    if D[i][0] == 0
        flag += 1
    end
}
if flag != 1
    p -1
    exit
end

D.sort!
b = Array.new(2*n)
e = Array.new(2*n)
l=0
f=0
t=1
while t<n
    if f==1
        k -= 1
    end
    if D[t].first!= (D[f].first+1)
        puts "-1"
        exit
    end
    p=k
    i = t
    while i<n
        break if D[i].first!=D[t].first
        if(p==0)
            f +=1
            p=k
        end
        if(p==0)
            puts("-1")
            exit
        end
        p -= 1
        if(f==t)
            puts("-1")
            exit
        end
        b[l]=D[f][1];
        e[l]=D[i][1];
        l+=1;i+=1;
    end
    f=t;
    t=i;
end

p l
l.times { |i|
    puts "#{b[i]} #{e[i]}"
}

n,k = gets.chomp!.split.map {|e| e.to_i}

D = gets.chomp!.split.map {|e| [e.to_i,0]}
flag = 0
n.times { |i|
    D[i][1]=i+1
    if D[i][0] == 0
        flag += 1
    end
}
if flag != 1
    p -1
    exit
end

D.sort!
# p D

cur = D[0][1]
kk1=0
kk2=0

road = Array.new(n){|e| e=Array.new}

road[0].push(cur)
p1 = -1
re = 1
ans1 = Array.new(3*n)
ans2 = Array.new(3*n)
cnt = Array.new(n+10,0)

for i in 1...n
    nxt = D[i][0]-1
    if nxt != p1
        kk1=0
        p1 = nxt
    end
    len = road[nxt].size
    # print "aaa:    "
    # p road[nxt]
    fg = 1
    while kk1<len
        if (cnt[road[nxt][kk1]]==k)||(nxt!=0&&cnt[road[nxt][kk1]]==k-1)
            kk1 += 1
            # puts "#{cnt[road[nxt][kk1]]} #{k} asd"
        else
            road[nxt+1].push(D[i][1])
            ans1[kk2] = road[nxt][kk1]
            ans2[kk2] = D[i][1]
            cnt[road[nxt][kk1]] +=1
            fg = 0
            kk2 += 1
            # print "bbb:    "
            # p ans1
            # p ans2
            break
        end
    end
    if fg == 1
        re = 0
        break
    end
end

if re == 0
    p -1
    #puts "adsasd"
    exit
end

p kk2
kk2.times { |i|
    printf("%d %d",ans1[i],ans2[i])
}

n,k = gets.chomp!.split.map {|e| e.to_i}

D = gets.chomp!.split.map {|e| [e.to_i,0]}
flag = 0
n.times { |i|
	D[i][1]=i+1
	if D[i][0] == 0
		flag += 1
	end
}
if flag != 1
	p -1
	exit
end

D.sort!
# p D

cur = D[0][1]
kk1=0
kk2=0

road = Array.new(n,Array.new)

road[0].push(cur)
p1 = -1
re = 1
ans1 = Array.new(3*n)
ans2 = Array.new(3*n)
cnt = Array.new(n+10,0)

for i in 1...n
	nxt = D[i][0]-1
	if nxt != p1
		kk1=0
		p1 = nxt
	end
	len = road[nxt].size
	# print "aaa:    "
	# p road[nxt]
	fg = 1
	while kk1<len
		if (cnt[road[nxt][kk1]]==k)||(nxt!=0&&cnt[road[nxt][kk1]]==k-1)
			kk1 += 1
			# puts "#{cnt[road[nxt][kk1]]} #{k} asd"
		else
			road[nxt+1].push(D[i][1])
			ans1[kk2] = road[nxt][kk1]
			ans2[kk2] = D[i][1]
			cnt[road[nxt][kk1]] +=1
			fg = 0
			kk2 += 1
			# print "bbb:    "
			# p ans1
			# p ans2
			break
		end
	end
	if fg == 1
		re = 0
		break
	end
end

if re == 0
	p -1
	#puts "adsasd"
	exit
end

kk2.times { |i|
	puts "#{ans1[i]} #{ans2[i]}"
}

n,k = gets.chomp!.split.map {|e| e.to_i}

D = gets.chomp!.split.map {|e| [e.to_i,0]}
flag = 0
n.times { |i|
	D[i][1]=i+1
	if D[i][0] == 0
		flag += 1
	end
}
if flag != 1
	p -1
	exit
end

D.sort!
# p D

cur = D[0][1]
kk1=0
kk2=0

road = Array.new(n,Array.new)

road[0].push(cur)
p1 = -1
re = 1
ans1 = Array.new(3*n)
ans2 = Array.new(3*n)
cnt = Array.new(n+10,0)

for i in 1...n
	nxt = D[i][0]-1
	if nxt != p1
		kk1=0
		p1 = nxt
	end
	len = road[nxt].size
	# print "aaa:    "
	# p road[nxt]
	fg = 1
	while kk1<len
		if (cnt[road[nxt][kk1]]==k)||(nxt!=0&&cnt[road[nxt][kk1]]==k-1)
			kk1 += 1
			# puts "#{cnt[road[nxt][kk1]]} #{k} asd"
		else
			road[nxt+1].push(D[i][1])
			ans1[kk2] = road[nxt][kk1]
			ans2[kk2] = D[i][1]
			cnt[road[nxt][kk1]] +=1
			fg = 0
			kk2 += 1
			# print "bbb:    "
			# p ans1
			# p ans2
			break
		end
	end
	if fg == 1
		re = 0
		break
	end
end

if re == 0
	p -1
	#puts "adsasd"
	exit
end

p kk2
kk2.times { |i|
	puts "#{ans1[i]} #{ans2[i]}"
}