Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.

Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

# coding: utf-8
EMPTY = '.'
WALL = '#'
ADDED_WALL = 'X'
PRESERVED = 'P'
n, m, k = gets.split.map(&:to_i)
C = Struct.new(:i, :j)
g = []
ec = [] # empty cells coordinates
n.times { |i|
    r = gets.chomp.split(//)
    for j in 0...m
        if r[j] == EMPTY
            ec << C.new(i, j)
        end
    end
    g << r
}

# k 개 블럭을 이용해 새로운 벽을 놓습니다
# 윗 줄이 완전히 막혀도 상관없지만,
# 블럭을 설치한 후에도 길은 모두 이어져 있어야합니다.
# 즉, 다음과 같이 섬이 만들어져서는 안됩니다.
# n = 4, m = 4
# ####
# ##..
# #.#.
# ###.
# 1. 전체 empty cell 을 카운트 합니다.
# 2. empty cell 을 DFS/BFS 로 순회하여, 1의 수치에서 k개 점을 제외한만큼 확보합니다.
# 3. 여전히 남아있는 셀들을 벽을 설치할 셀로 마크합니다.
# 불행히도 처음에 생각한 이웃한 empty cell이 적은걸 마킹하는 방법은 실패합니다.
#p "empty cells : #{ec.length}, add wall block: #{k}, preserve goal: #{ec.length - k}"
goal = ec.length - k
collected = []
q = [ec.first]
while collected.length < goal
    c = q.shift
    if g[c.i][c.j] != EMPTY
        next
    end
    collected << c
    # p collected
    g[c.i][c.j] = PRESERVED
    #puts "==> preserved #{collected.length}/#{ec.length} #{c}"
    cands = [C.new(c.i+1, c.j), C.new(c.i-1, c.j), C.new(c.i, c.j+1), C.new(c.i, c.j-1)]
    for cand in cands
        if cand.i >= 0 && cand.i < n && cand.j >= 0 && cand.j < m
            if g[cand.i][cand.j] == EMPTY
                q << cand
            end
        end
    end
end

puts g.map(&:join).join("\n").gsub(EMPTY, ADDED_WALL).gsub(PRESERVED, EMPTY)
#puts g.map(&:join).join("").count(EMPTY)

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "X"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run BFS
def bfs(root, maze, depth)
  queue = Array.new(depth)
  queue[0] = root
  visited = Array.new(maze.length) { Array.new(maze[0].length, false) }
  front = 0; back = 1;
  while true
    root = queue[front]
    front = front + 1
    maze[root[0]][root[1]] = "."
    return if front == depth
    for child in children(root, maze) do
        unless visited[child[0]][child[1]]
            queue[back] = child
            back = back + 1
            visited[child[0]][child[1]] = true
        end
    end
  end
end

# Print maze
def print_maze(maze)
  puts maze.map { |row| row.join("") }
end

# Initialize variables
maze = []; root = [0]; depth = 0; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "X"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
bfs(root, maze, depth)

# Print maze
print_maze(maze)

@di = [-1, 0, 1, 0]
@dj = @di.reverse

def ok(i, j)
  return false if i < 0 || i >= @n || j < 0 || j >= @m || @maze[i][j] != '.'
  return true
end

def bfs(si, sj)
  qi = 0
  qj = 0
  q = Array.new(@n * @m)
  q[qj] = [si, sj]
  qj += 1
  while qi < qj
    arr = q[qi]
    qi += 1
    i = arr[0]
    j = arr[1]
    next if @vis[i][j]
    @vis[i][j] = true
    @reached += 1
    break if @reached == @target
    4.times { |d|
      ni = i + @di[d]
      nj = j + @dj[d]
      if ok(ni, nj)
        q[qj] = [ni, nj]
        qj += 1
      end
    }
  end
end

@n, @m, k = gets.strip.split.map(&:to_i)
@maze = Array.new(@n)
@vis = Array.new(@n) {Array.new(@m) { false }}
s = 0
@n.times {|i|
  @maze[i] = gets.strip.split("")
  s += @maze[i].select{|c| c == '.'}.count
}
@reached = 0
@target = s - k
@n.times {|i|
  done = false
  @m.times {|j|
    # puts " > #{i}, #{j}, #{@maze[i][j].class}"
    if @maze[i][j] == '.'
      done = true
      bfs(i, j)
      break
    end
  }
  break if done
}

# puts @maze.map{|s| s.join("")}.join("\n")

@n.times {|i|
  @m.times {|j|
    if @maze[i][j] == '.' && !@vis[i][j]
      @maze[i][j] = 'X'
    end
  }
}
@maze.map!{|r| r.join("")}
out = @maze.join("\n")
$stdout.print out

# coding: utf-8
EMPTY = '.'
WALL = '#'
ADDED_WALL = 'X'
PRESERVED = 'P'
n, m, k = gets.split.map(&:to_i)
C = Struct.new(:i, :j)
g = []
ec = [] # empty cells coordinates
n.times { |i|
    r = gets.chomp.split(//)
    for j in 0...m
        if r[j] == EMPTY
            ec << C.new(i, j)
        end
    end
    g << r
}

# k 개 블럭을 이용해 새로운 벽을 놓습니다
# 윗 줄이 완전히 막혀도 상관없지만,
# 블럭을 설치한 후에도 길은 모두 이어져 있어야합니다.
# 즉, 다음과 같이 섬이 만들어져서는 안됩니다.
# n = 4, m = 4
# ####
# ##..
# #.#.
# ###.
# 1. 전체 empty cell 을 카운트 합니다.
# 2. empty cell 을 DFS/BFS 로 순회하여, 1의 수치에서 k개 점을 제외한만큼 확보합니다.
# 3. 여전히 남아있는 셀들을 벽을 설치할 셀로 마크합니다.
# 불행히도 처음에 생각한 이웃한 empty cell이 적은걸 마킹하는 방법은 실패합니다.

goal = ec.length - k
collected = []
q = [ec.first]
while collected.length < goal
    c = q.shift
    collected << c
    # p collected
    g[c.i][c.j] = PRESERVED
    cands = [C.new(c.i+1, c.j), C.new(c.i, c.j+1), C.new(c.i-1, c.j), C.new(c.i, c.j-1)]
    for cand in cands
        if cand.i >= 0 && cand.i < n && cand.j >= 0 && cand.j < m
            if g[cand.i][cand.j] == EMPTY
                q << cand
            end
        end
    end
end

puts g.map(&:join).join("\n").gsub(EMPTY, ADDED_WALL).gsub(PRESERVED, EMPTY)

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "X"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run BFS
def bfs(root, maze, depth)
  queue = []; at = 0;
  queue.push(root)
  while (queue.size != 0)
    root = queue.shift
    maze[root[0]][root[1]] = "."
    at = at + 1
    return if at == depth
    for child in children(root, maze) do
      queue.push(child)
    end
  end
end

# Run DFS
def dfs(root, traversal, maze, depth)
    maze[root[0]][root[1]] = "."
    traversal.push(root)
    for child in children(root, maze) do
        if traversal.length < depth
            dfs(child, traversal, maze, depth)
        end
    end
end

# Initialize variables
maze = []; root = [0]; depth = 0; traversal = []; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "X"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
bfs(root, maze, depth)
# dfs(root, traversal, maze, depth)

# Print maze
for i in 0..(n - 1) do
    puts maze[i].join("")
end

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "x"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run DFS
def dfs(root, traversal, maze, depth)
    maze[root[0]][root[1]] = "."
    traversal.push(root)
    for child in children(root, maze) do
        if traversal.length < depth
            dfs(child, traversal, maze, depth)
        end
    end
end

# Initialize variables
maze = []; root = [0]; depth = 0; traversal = []; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "X"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
dfs(root, traversal, maze, depth)

# Print maze
for i in 0..(n - 1) do
    puts maze[i].join("")
end

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "X"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run BFS
def bfs(root, maze, depth)
  queue = []; at = 0;
  queue.push(root)
  while (queue.size != 0)
    root = queue.shift
    maze[root[0]][root[1]] = "."
    at = at + 1

    puts
    puts at
    print root
    puts
    print_maze(maze)

    return if at == depth
    for child in children(root, maze) do
      queue.push(child) unless queue.include?(child)
    end
  end
end

# Run DFS
def dfs(root, traversal, maze, depth)
    maze[root[0]][root[1]] = "."
    traversal.push(root)
    for child in children(root, maze) do
        if traversal.length < depth
            dfs(child, traversal, maze, depth)
        end
    end
end

def print_maze(maze)
    for i in 0..(maze.length - 1) do
        puts maze[i].join("")
    end
end

# Initialize variables
maze = []; root = [0]; depth = 0; traversal = []; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "X"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
bfs(root, maze, depth)
# dfs(root, traversal, maze, depth)

puts
puts depth
puts

# Print maze
print_maze(maze)

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "x"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run DFS
def dfs(root, traversal, maze, depth)
    maze[root[0]][root[1]] = "."
    traversal.push(root)
    for child in children(root, maze) do
        if traversal.length < depth
            dfs(child, traversal, maze, depth)
        end
    end
end

# Initialize variables
maze = []; root = [0]; depth = 0; traversal = []; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "x"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
dfs(root, traversal, maze, depth)

# Print maze
for i in 0..(n - 1) do
    puts maze[i].join("")
end

# Is the curren node valid?
def valid(node, maze)
    return false if node.min < 0
    return false if node[0] >= maze.length
    return false if node[1] >= maze[0].length
    return false if maze[node[0]][node[1]] != "X"
    return true
end

# Nodes connected to node
def children(node, maze)
    children = []
    offsets = [[-1,0],[1,0],[0,-1],[0,1]]
    for offset in offsets
        nebr = [node[0] + offset[0] ,node[1] + offset[1]]
        children.push(nebr) if valid(nebr, maze)
    end
    return children
end

# Run BFS
def bfs(root, maze, depth)
  queue = Array.new(depth)
  queue[0] = root
  visited = Array.new(maze.length) { Array.new(maze[0].length, false) }
  front = 0; back = 1;
  while true
    root = queue[front]
    front = front + 1
    maze[root[0]][root[1]] = "."
    return if front == depth
    for child in children(root, maze) do
        unless visited[child[0]][child[1]]
            queue[back] = child
            back = back + 1
        end
    end
  end
end

# Print maze
def print_maze(maze)
  puts maze.map { |row| row.join("") }
end

# Initialize variables
maze = []; root = [0]; depth = 0; c = 0;

# Read input
n, m, k = gets.strip.split.map{|s| s.to_i}
n.times {maze.push(gets.strip.split(""))}

# Convert all . to x
for i in 0..(n - 1) do
     for j in 0..(m - 1) do
          if maze[i][j] == "."
            maze[i][j] = "X"
            c = c + 1
            root = [i,j]
          end
     end
end

# Size of required clearing
depth = c - k

# Solve maze
bfs(root, maze, depth)

# Print maze
print_maze(maze)


Andrew has $$$n$$$ piles with stones. The $$$i$$$-th pile contains $$$a_i$$$ stones. He wants to make his table clean so he decided to put every stone either to the $$$1$$$-st or the $$$n$$$-th pile.Andrew can perform the following operation any number of times: choose $$$3$$$ indices $$$1 \le i < j < k \le n$$$, such that the $$$j$$$-th pile contains at least $$$2$$$ stones, then he takes $$$2$$$ stones from the pile $$$j$$$ and puts one stone into pile $$$i$$$ and one stone into pile $$$k$$$. Tell Andrew what is the minimum number of operations needed to move all the stones to piles $$$1$$$ and $$$n$$$, or determine if it's impossible.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the minimum number of operations needed to move stones to piles $$$1$$$ and $$$n$$$, or print $$$-1$$$ if it's impossible.

NoteIn the first test case, it is optimal to do the following:   Select $$$(i, j, k) = (1, 2, 5)$$$. The array becomes equal to $$$[2, 0, 2, 3, 7]$$$.  Select $$$(i, j, k) = (1, 3, 4)$$$. The array becomes equal to $$$[3, 0, 0, 4, 7]$$$.  Twice select $$$(i, j, k) = (1, 4, 5)$$$. The array becomes equal to $$$[5, 0, 0, 0, 9]$$$. This array satisfy the statement, because every stone is moved to piles $$$1$$$ and $$$5$$$.  There are $$$4$$$ operations in total.In the second test case, it's impossible to put all stones into piles with numbers $$$1$$$ and $$$3$$$:   At the beginning there's only one possible operation with $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 1, 2]$$$.  Now there is no possible operation and the array doesn't satisfy the statement, so the answer is $$$-1$$$. In the third test case, it's optimal to do the following:   Select $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 0, 2]$$$. This array satisfies the statement, because every stone is moved to piles $$$1$$$ and $$$3$$$.  The is $$$1$$$ operation in total.In the fourth test case, it's impossible to do any operation, and the array doesn't satisfy the statement, so the answer is $$$-1$$$.

def stone(arr)
  if arr.length == 3 and arr[1]%2!=0
    return -1
  elsif arr[1,arr.length-2].sum == arr[1,arr.length-2].length
    return -1
  else
    idx = 1
    move = 0
    while idx < arr.length-1
      if arr[idx]%2==0
        move+=arr[idx]/2
      else
        move+=(arr[idx]+1)/2
      end
      idx+=1
    end
  end
  return move
end

t = gets.chomp.to_i
t.times do
  len = gets.chomp
  arr = gets.chomp.split(' ').reject(&:empty?).map(&:to_i)
  puts stone(arr)
end


Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n2)) — the size of the board and the number of rooks.  Each of the next m lines contains integers xi and yi (1 ≤ xi, yi ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.

Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.

NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.

def getRest n, rowslength, colslength
  count = n*n;
  count = count - (n * rowslength);
  count = count - ((n - rowslength) * colslength);
  return count;
end

n,m = gets.split(" ").map{|i| i.to_i}
count = n*n;
rows = {};
rowsC = 0;
cols = {};
colsC = 0;
res = "";

m.times do |i|
  x, y = gets.split(" ").map{|i| i.to_i}
  if rows[x].nil?
    rows[x] = 1;
    rowsC = rowsC + 1
  end
  if cols[y].nil?
    cols[y] = 1;
    colsC = colsC + 1
  end
  res << getRest(n, rowsC, colsC).to_s
  if i != (m-1)
    res << " "
  end
end

puts res

n, m = gets.chomp.split.map(&:to_i)
cols = {}
rows = {}
ans = []
m.times do
  i, j = gets.chomp.split.map(&:to_i)
  rows[i] = true
  cols[j] = true

  ans << (n - rows.length) * (n - cols.length)
end
puts ans.join(' ')

#!/usr/bin/ruby

require 'set'

n, m = gets.chomp.split.map(&:to_i)
col = Array.new(n+1){ |i| 0 }
row = Array.new(n+1){ |i| 0 }
scol = Set.new
srow = Set.new
res = n * n
ans = []
for i in 0...m do
  x, y = gets.chomp.split.map(&:to_i)
  unless col[x] == 1 && row[y] == 1
    csz = scol.size
    rsz = srow.size
    cmr = n - 1 - csz + col[x]
    rmr = n - 1 - rsz + row[y]
    if col[x] == 1
      res -= cmr
    elsif row[y] == 1
      res -= rmr
    else
      res -= rmr + cmr + 1
    end
  end
  col[x] = row[y] = 1
  scol << x
  srow << y
  ans.push( res )
end
puts ans.join(" ")

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

N, M = gis
rooks = ngis M

ans = []

w = N
h = N

rows = [true] * N
cols = [true] * N

rooks.each do |y, x|
    if rows[y - 1]
        h -= 1
        rows[y - 1] = false
    end
    if cols[x - 1]
        w -= 1
        cols[x - 1] = false
    end
    ans << h * w
end

puts ans * ' '

n,m=gets.split.map{|e| e.to_i}
ans=[]
xs={}
ys={}
n2=n*n

m.times{
	x,y=gets.split.map{|e| e.to_i}
	f1=xs.key?(x)
	f2=ys.key?(y)
	if f1==true && f2==true then
		#
	elsif f1==false && f2==true then
		n2=n2-(n-ys.size)
	elsif f1==true && f2==false then
		n2=n2-(n-xs.size)

	else
		n2=n2-(n*2-xs.size-ys.size)+1
	end
	ans<<n2
	xs[x]=1
	ys[y]=1
}
puts ans*" "

require "set"
n, m = gets.split.map(&:to_i)
ans = []
rows_with_rooks = Set.new
cols_with_rooks = Set.new

m.times do |i|
	r, c = gets.split.map(&:to_i)
	rows_with_rooks << r
	cols_with_rooks << c
	ans << (n-rows_with_rooks.size)*(n-cols_with_rooks.size)
end
puts ans.join(" ")

n, m = gets.chomp.split.map(&:to_i)
ans = []
files = Hash.new(0)
ranks = Hash.new(0)
m.times do
  x, y = gets.chomp.split.map(&:to_i)
  files[x] = 1
  ranks[y] = 1
  ans << (n - files.size) * (n - ranks.size)
end
puts ans.*' '

require 'set'
n,m = gets.split.map(&:to_i)
r,c = Set.new, Set.new
m.times do
  x,y = gets.split.map(&:to_i)
  r << x
  c << y
  print (n-r.size) * (n-c.size), " "
end

n, m = gets.split.map { |x| x.to_i }

acc_x = 0
acc_y = 0
vis_x = Array.new(n + 1)
vis_y = Array.new(n + 1)
cnt = n * n
ans = []

m.times do
	x, y = gets.split.map { |x| x.to_i }
	if !vis_x[x]
		vis_x[x] = true
		cnt -= n - acc_y
		acc_x += 1
	end
	if !vis_y[y]
		vis_y[y] = true
		cnt -= n - acc_x
		acc_y += 1
	end
	ans << cnt
end
puts ans.join ' '

n,m=gets.split.map{|e| e.to_i}
ans=[]
xs={}
ys={}
n2=n*n

m.times{
	x,y=gets.split.map{|e| e.to_i}
	f1=xs.key?(x)
	f2=ys.key?(y)
	if f1==true && f2==true then
		#
	elsif f1==false && f2==true then
		n2=n2-(n-xs.size)
	elsif f1==true && f2==false then
		n2=n2-(n-ys.size)
	else
		n2=n2-(n*2-xs.size-ys.size)+1
	end
	ans<<n2
	xs[x]=1
	ys[y]=1
}
puts ans*" "


Tomorrow is a difficult day for Polycarp: he has to attend $$$a$$$ lectures and $$$b$$$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $$$c$$$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $$$d$$$ practical classes, after which it is unusable.Polycarp's pencilcase can hold no more than $$$k$$$ writing implements, so if Polycarp wants to take $$$x$$$ pens and $$$y$$$ pencils, they will fit in the pencilcase if and only if $$$x + y \le k$$$.Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is described by one line containing five integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ and $$$k$$$, separated by spaces ($$$1 \le a, b, c, d, k \le 100$$$) — the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

For each test case, print the answer as follows: If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer $$$-1$$$. Otherwise, print two non-negative integers $$$x$$$ and $$$y$$$ — the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

NoteThere are many different answers for the first test case; $$$x = 7$$$, $$$y = 1$$$ is only one of them. For example, $$$x = 3$$$, $$$y = 1$$$ is also correct.$$$x = 1$$$, $$$y = 3$$$ is the only correct answer for the third test case.

readline.to_i.times do
  a,b,c,d,k = readline.split.map(&:to_i)
  x,y = ((a-1)/c)+1,((b-1)/d)+1
  if x+y <= k
    print(x," ",y,"\n")
  else
    p -1
  end
end

T = gets.to_i
T.times do
  a,b,c,d,k = gets.split.map(&:to_f)
  x = (a/c).ceil
  y = (b/d).ceil
  if x + y <= k
    puts "#{x} #{y}"
  else
    p -1
  end
end

t = gets.to_i
t.times do
  a, b, c, d, k = gets.split.map(&:to_f)
  s = (a/c).ceil.to_i
  t = (b/d).ceil.to_i
  if s + t <= k
    puts "#{s} #{t}"
  else
    puts -1
  end
end

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

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

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

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
t = gi
ans=[]

t.times do |i|
  a,b,c,d,k=gsmi
  c1 = (a.to_f/c).ceil
  c2 = (b.to_f/d).ceil
  if k-c1<c2
    ans << -1
  else
    ans << [c1, k-c1].join(" ")
  end
end
puts ans

t = gets.to_i
t.times do
  a, b, c, d, k = gets.split.map &:to_i
  x, y = (a + c - 1)/c, (b + d - 1)/d
  puts x + y <= k ? "#{x} #{y}" : -1
end

t = gets.to_i
t.times do
  a, b, c, d, k = gets.split.map &:to_i
  x, y = (a + c)/c, (b + d)/d
  puts x + y <= k ? "#{x} #{y}" : -1
end


You are given a string $$$s$$$. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each representing a test case. Each line contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$); each character of $$$s$$$ is either 0 or 1.

Print $$$t$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th testcase (the minimum number of 0's that you have to erase from $$$s$$$).

NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

T = gets.to_i

T.times do
  s = gets.chomp
  l = s.size
  ans = 0
  mode = :none
  cnt = 0

  (l - 1).times do |i|
    if mode == :count
      cnt += 1
    end

    if s[i] == '1' && s[i + 1] == '0'
      mode = :count
    elsif s[i] == '0' && s[i + 1] == '1'
      ans += cnt
      cnt = 0
      mode = :none
    end
  end

  puts ans
end

n = gets.to_i

n.times {
  s = gets.chomp
  while s[0] == "0"
    s = s[1..-1]
  end
  s = s.reverse
  while s[0] == "0"
    s = s[1..-1]
  end
  puts s.count("0")
}

1.upto(gets.to_i) do
  s = gets.chomp

  s.gsub!(/^0*/, '')
  s.gsub!(/0*$/, '')

  puts s.count('0')
end

t=gets.to_i
(1).upto(t) do
  s=gets.strip.split('')
  ans=0
  flag=false
  counter=0
  s.each do |i|
    flag=true if i=='1'
    ans=counter if i=='1'
    counter+=1 if i=='0' and flag
  end
  puts ans
end


Nastia has $$$2$$$ positive integers $$$A$$$ and $$$B$$$. She defines that:  The integer is good if it is divisible by $$$A \cdot B$$$;  Otherwise, the integer is nearly good, if it is divisible by $$$A$$$. For example, if $$$A = 6$$$ and $$$B = 4$$$, the integers $$$24$$$ and $$$72$$$ are good, the integers $$$6$$$, $$$660$$$ and $$$12$$$ are nearly good, the integers $$$16$$$, $$$7$$$ are neither good nor nearly good.Find $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$A$$$ and $$$B$$$ ($$$1 \le A \le 10^6$$$, $$$1 \le B \le 10^6$$$) — numbers that Nastia has.

For each test case print:    "YES" and $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.  "NO" if no answer exists.  YES NO If there are multiple answers, print any.

NoteIn the first test case: $$$60$$$ — good number; $$$10$$$ and $$$50$$$ — nearly good numbers.In the second test case: $$$208$$$ — good number; $$$169$$$ and $$$39$$$ — nearly good numbers.In the third test case: $$$154$$$ — good number; $$$28$$$ and $$$182$$$ — nearly good numbers.

t = gets.chomp.to_i

t.times do
  a, b = gets.chomp.split(" ").map(&:to_i)
  if b == 1
    puts "NO"
    next
  end
  puts "YES"
  puts "#{a} #{a*b} #{a*(b+1)}"
end

$, = " "
gets.to_i.times do
    a, b = gets.split.map &:to_i
    if b == 1
        puts "NO"
    else
        puts "YES"
        print a, a * b, a * (b + 1), "\n"
    end
end

t = gets.to_i
while t.positive?
  a, b = gets.split.map(&:to_i)
  if b == 1
    puts 'NO'
  else
    puts 'YES'
    print "#{a * b} #{a} #{a * b + a}\n"
  end
  t -= 1
end

t = gets.chomp.to_i

t.times do
  a, b = gets.chomp.split(" ").map(&:to_i)
  puts "YES"
  puts "#{a} #{a*(b-1)} #{a*b}"
end


Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:   $$$f(0) = a$$$;  $$$f(1) = b$$$;  $$$f(n) = f(n-1) \oplus f(n-2)$$$ when $$$n > 1$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. You are given three integers $$$a$$$, $$$b$$$, and $$$n$$$, calculate $$$f(n)$$$.You have to answer for $$$T$$$ independent test cases.

The input contains one or more independent test cases. The first line of input contains a single integer $$$T$$$ ($$$1 \le T \le 10^3$$$), the number of test cases. Each of the $$$T$$$ following lines contains three space-separated integers $$$a$$$, $$$b$$$, and $$$n$$$ ($$$0 \le a, b, n \le 10^9$$$) respectively.

NoteIn the first example, $$$f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$$$.

t = readline.to_i

t.times do
  a,b,n = readline.split.map(&:to_i)
  case n % 3
  when 0
    puts a
  when 1
    puts b
  when 2
    puts a^b
  end
end

readline.to_i.times do
  a,b,n = readline.split.map(&:to_i)
  p [a,b,a^b][n%3]
end

gets.to_i.times{
a=gets.split.map &:to_i
a[a[2]%3^1]=0
p a[0]^a[1]
}

gets.to_i.times do
    a,b,n = gets.split.map(&:to_i)
    if n%3 == 0
        puts a
    elsif n%3 == 1
        puts b
    else
        puts a^b
    end
end

def solve
	n = gets.strip.split(' ').map(&:to_i)
	a1 = [n[0], n[1], n[0] ^ n[1]]
	puts a1[n[2] % 3]
end

gets.strip.to_i.times {
	solve
}

gets.to_i.times do
  a, b, n = gets.split.map &:to_i
  p [a, b, a ^ b][n%3]
end

def solve
	n = gets.strip.split(' ').map(&:to_i)
	a1 = [n[0], n[1], n[0] ^ n[1]]
	if n[2] < 3
		puts a1[n[2]]
	else
		a1[0], a1[1] = a1[1], a1[0]
		puts a1[n[2] % 3]
	end
end

gets.strip.to_i.times {
	solve
}


You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi — the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .

The only line contains integer n (1 ≤ n ≤ 5·105).

Print 2n integers — the permuted array a that minimizes the value of the sum s.

n = gets.to_i
a = []
if n.odd? then
    1.step(n, 2) do |i|
        a.push i
    end
    (n-2).step(1, -2) do |i|
        a.push i
    end
    a.push n
    2.step(n, 2) do |i|
        a.push i
    end
    (n-1).step(2, -2) do |i|
        a.push i
    end
else
    1.step(n, 2) do |i|
        a.push i
    end
    (n-1).step(1, -2) do |i|
        a.push i
    end
    a.push n
    2.step(n, 2) do |i|
        a.push i
    end
    (n-2).step(2, -2) do |i|
        a.push i
    end
end
puts a.join(' ')

i = 1
n = gets.chomp.to_i
while i < n
  print "#{i} "
  i += 2
end
i -= 2
print "#{n} " if n % 2 == 1 and n != i
while i > 0
  print "#{i} "
  i -= 2
end
i = 2;
while i < n
  print "#{i} "
  i += 2
end
i -= 2
print "#{n} " if n % 2 == 0 and n != i
while i > 0
  print "#{i} "
  i -= 2
end
i = 2
puts n


A sequence of $$$n$$$ non-negative integers ($$$n \ge 2$$$) $$$a_1, a_2, \dots, a_n$$$ is called good if for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following condition holds true: $$$$$$a_1 \: \& \: a_2 \: \& \: \dots \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: \dots \: \& \: a_n,$$$$$$ where $$$\&$$$ denotes the bitwise AND operation.You are given an array $$$a$$$ of size $$$n$$$ ($$$n \geq 2$$$). Find the number of permutations $$$p$$$ of numbers ranging from $$$1$$$ to $$$n$$$, for which the sequence $$$a_{p_1}$$$, $$$a_{p_2}$$$, ... ,$$$a_{p_n}$$$ is good. Since this number can be large, output it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), denoting the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, where the $$$i$$$-th line contains the number of good permutations in the $$$i$$$-th test case modulo $$$10^9 + 7$$$.

NoteIn the first test case, since all the numbers are equal, whatever permutation we take, the sequence is good. There are a total of $$$6$$$ permutations possible with numbers from $$$1$$$ to $$$3$$$: $$$[1,2,3]$$$, $$$[1,3,2]$$$, $$$[2,1,3]$$$, $$$[2,3,1]$$$, $$$[3,1,2]$$$, $$$[3,2,1]$$$.In the second test case, it can be proved that no permutation exists for which the sequence is good.In the third test case, there are a total of $$$36$$$ permutations for which the sequence is good. One of them is the permutation $$$[1,5,4,2,3]$$$ which results in the sequence $$$s=[0,0,3,2,0]$$$. This is a good sequence because   $$$ s_1 = s_2 \: \& \: s_3 \: \& \: s_4 \: \& \: s_5 = 0$$$,  $$$ s_1 \: \& \: s_2 = s_3 \: \& \: s_4 \: \& \: s_5 = 0$$$,  $$$ s_1 \: \& \: s_2 \: \& \: s_3 = s_4 \: \& \: s_5 = 0$$$,  $$$ s_1 \: \& \: s_2 \: \& \: s_3 \: \& \: s_4 = s_5 = 0$$$.

RECURSIVE = false

def fact(n, p)
  return 1.upto(n).reduce(1.0) {|acc, x| (acc * x) % p } unless RECURSIVE

  if n <= 1
    return 1
  else
    return (n * fact(n - 1, p)) % p
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_f
  a = gets.to_s.split.map {|x| x.to_i }

  mask = ~a.reduce(0xFFFFFFFF) {|acc, x| acc & x }
  zerocnt = a.reduce(0) {|acc, val| acc + (((val & mask) == 0) ? 1 : 0) }

  p = 10 ** 9 + 7
  permcnt = fact(n - 2, p) * zerocnt % p * (zerocnt - 1) % p
  printf("%d\n", permcnt)
end

RECURSIVE = false

def fact(n, p)
  return 1.upto(n).reduce(1) {|acc, x| (acc * x) % p } unless RECURSIVE

  if n <= 1
    return 1
  else
    return (n * fact(n - 1, p)) % p
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_f
  a = gets.to_s.split.map {|x| x.to_i }

  mask = ~a.reduce(0xFFFFFFFF) {|acc, x| acc & x }
  zerocnt = a.reduce(0) {|acc, val| acc + (((val & mask) == 0) ? 1 : 0) }

  permcnt = fact(n - 2, 10 ** 9 + 7) * zerocnt * (zerocnt - 1)
  printf("%d\n", permcnt % (10 ** 9 + 7))
end

def fact(n, p)
  result = 1
  for i in (1 .. n) do
    result = (result * i) % p
  end
  result
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  bitcounters = [0] * 32
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  valmask = 0
  0.upto(31) do |bitidx|
    bitmask = 1 << bitidx
    a.each do |val|
       if val & bitmask != 0
         bitcounters[bitidx] += 1
       end
    end
    valmask |= bitmask if bitcounters[bitidx] != a.size
  end

  zerocnt = 0
  a.each {|val| zerocnt += 1 if (val & valmask) == 0 }

  permcnt = fact(n - 2, 10 ** 9 + 7) * zerocnt * (zerocnt - 1)
  printf("%d\n", permcnt % (10 ** 9 + 7))
end

RECURSIVE = false

def fact(n, p)
  return 1.upto(n).reduce(1.0) {|acc, x| (acc * x) % p } unless RECURSIVE

  if n <= 1
    return 1
  else
    return (n * fact(n - 1, p)) % p
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_f
  a = gets.to_s.split.map {|x| x.to_i }

  mask = ~a.reduce(0xFFFFFFFF) {|acc, x| acc & x }
  zerocnt = a.reduce(0) {|acc, val| acc + (((val & mask) == 0) ? 1 : 0) }

  permcnt = fact(n - 2, 10 ** 9 + 7) * zerocnt * (zerocnt - 1)
  printf("%d\n", permcnt % (10 ** 9 + 7))
end

def fact(n, p)
  result = 1
  for i in (1 .. n) do
    result = (result * i) % p
  end
  result
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  bitcounters = [0] * 32
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  valmask = 0
  0.upto(31) do |bitidx|
    bitmask = 1 << bitidx
    a.each do |val|
       if val & bitmask != 0
         bitcounters[bitidx] += 1
       end
    end
    valmask |= bitmask if bitcounters[bitidx] != a.size
  end

  zerocnt = 0
  a.each {|val| zerocnt += 1 if (val & valmask) == 0 }

  permcnt = (fact(n, 10 ** 9 + 7) * zerocnt * (zerocnt - 1) / (n * (n - 1)))
  printf("%d\n", permcnt % (10 ** 9 + 7))
end


Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?

The first line contains integer n (1 ≤ n ≤ 50000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.

Print the total minimum number of moves.

n=gets.to_i
xs=gets.split.map(&:to_i)
m=xs.inject(:+)/n

k,r=0,0

for i in (0...n)
  k+=xs[i]-m
  r+=k.abs
end

p r


Your company was appointed to lay new asphalt on the highway of length $$$n$$$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $$$g$$$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $$$b$$$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $$$g$$$ good days, $$$b$$$ bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days $$$1, 2, \dots, g$$$ are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $$$n = 5$$$ then at least $$$3$$$ units of the highway should have high quality; if $$$n = 4$$$ then at least $$$2$$$ units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains three integers $$$n$$$, $$$g$$$ and $$$b$$$ ($$$1 \le n, g, b \le 10^9$$$) — the length of the highway and the number of good and bad days respectively.

Print $$$T$$$ integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.

NoteIn the first test case, you can just lay new asphalt each day, since days $$$1, 3, 5$$$ are good.In the second test case, you can also lay new asphalt each day, since days $$$1$$$-$$$8$$$ are good.

T = gets.to_i

def f(day, n, g, b)
  l = (n / 2.0).ceil
  unit = g + b
  good_cnt = 0
  bad_cnt = 0

  block = day / unit
  remain = day - block * unit
  good_cnt += g * block

  if remain > 0
    good_cnt += [remain, g].min
  end

  l <= good_cnt
end

T.times do
  n, g, b = gets.split.map(&:to_i)

  ng = 0
  ok = n * (g + b)

  while (ok - ng).abs > 1
    mid = (ok + ng) / 2

    if f(mid, n, g, b)
      ok = mid
    else
      ng = mid
    end
  end

  puts [n, ok].max
end


Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.

The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.

In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d\n")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = gets.chomp.scanf("%d %d")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in (n-1).downto(i)
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
				d[i] += 1
				d[j] += 1
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d %d\n")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d %d\n")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in (n-1).downto(i)
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
				d[i] += 1
				d[j] += 1
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d\n")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d%d\n")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in (n-1).downto(i)
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
				d[i] += 1
				d[j] += 1
			end
		end
	end
end

require 'scanf'

n, m = scanf("%d %d")
d = Array.new(n) { 0 }

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d %d").map { |x| x - 1 }
	puts "a = #{a}, b = #{b}"
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'
require 'matrix'

class Matrix
	def []=(i,j,x)
		@rows[i][j] = x
	end
end

n, m = scanf("%d %d")
g = Matrix.build(n) { 0 }
d = Array.new(n) { 0 }

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d %d").map { |x| x - 1 }
	g[a, b] = 1
	g[b, a] = 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d%d")
	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

n, m = scanf("%d %d")
d = Array.new(n) { 0 }

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d %d").map { |x| x - 1 }
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

n, m = scanf("%d%d")
d = Array.new(n) { 0 }

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d%d")
	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d%d")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in (n-1).downto(i)
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
				d[i] += 1
				d[j] += 1
			end
		end
	end
end

require 'scanf'

n, m = scanf("%d %d")
d = Array.new(n) { 0 }

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf("%d %d")
	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d\n")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = gets.chomp.scanf("%d %d")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf(" %d%d")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = scanf(" %d%d")
#	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
#puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in (n-1).downto(i)
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
				d[i] += 1
				d[j] += 1
			end
		end
	end
end

require 'scanf'

class UnionFindSet
	def initialize(n)
		@n = n
		@bel = Array.new(n) { |x| x }
	end

	def find(x)
		@bel[x] = find(@bel[x]) unless @bel[x] == x
		@bel[x]
	end

	def union(x, y)
		@bel[find(x)] = find(y)
	end
end

n, m = scanf("%d%d\n")
d = Array.new(n) { 0 }

uf = UnionFindSet.new(n)
joinEdge = 0
for i in 1..m
	a, b = gets.chomp.scanf("%d %d")
	puts "a = #{a}, b = #{b}"
	a -= 1
	b -= 1
	d[a] += 1
	d[b] += 1
	joinEdge += 1 if uf.find(a) == uf.find(b)
	uf.union(a, b)
end

maxDeg = d.max
puts "max deg = #{maxDeg}, joinEdge = #{joinEdge}, n = #{n}, m = #{m}"

if maxDeg > 2
	puts "NO"
elsif joinEdge > 0
	if maxDeg == 2 and joinEdge == 1 and n == m
		puts "YES"
		puts "0"
	else
		puts "NO"
	end
else
	puts "YES"
	puts "#{n - m}"
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2 and uf.find(i) != uf.find(j)
				puts "#{i+1} #{j+1}"
				uf.union(i, j)
				d[i] += 1
				d[j] += 1
			end
		end
	end
	for i in 0...n
		for j in i+1...n
			if d[i] < 2 and d[j] < 2
				puts "#{i+1} #{j+1}"
			end
		end
	end
end


Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds:   $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length);  in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.

Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record.

NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one.

DBG = !true
n,m = gets.split.map{|z| z.to_i}
arcs = Array.new(n).map{[]}
for i in 0...m
  x,y = gets.split.map{|z| z.to_i}
  next if x==y  # ignore self loops
  x -= 1
  y -= 1
  arcs[x] << y
  arcs[y] << x
  #a,b = gets.split
  #a = a.to_i
  #b = b.to_i
end
for i in 0...n
  arcs[i].uniq!
end

if DBG
  print arcs
  puts ""
end

def pushh(h, v)
  if h.empty?
    h << v
    return
  elsif h.size == 1
    if v >= h[0]
      h << v
    else
      h.unshift(v)
    end
    return
  end
  puts "pushh #{v} called" if DBG
  mn = 0
  mx = h.size-1
  if v <= h[0]
    h[0,0] = v if v < h[0]
  elsif  h[mx] <= v
    h << v if h[mx] < v
  else
    while mn+1 < mx
      mid = (mn+mx)/2
      if h[mid] < v
        mn = mid
      else
        mx = mid
      end
    end
    h[mx,0] = v if h[mn] < v && v < h[mx]
  end

end

done = Array.new(n, false)
seq = [1]
done[0] = true
conn = arcs[0].sort
for x in conn
  done[x] = true
end
for i in 1...n
  if DBG
    print "i #{i} conn/done "
    print conn
    print done
    puts ""
  end
  nxt = conn.shift
  puts "picked #{nxt}" if DBG
  #done[nxt] = true
  seq << nxt + 1
  nxcon = arcs[nxt]
  for x in nxcon
    if !done[x]
      done[x] = true
      pushh(conn, x)
      #p = conn.bsearch_index{|z| z>=x}
      #if p.nil?
      #  conn << x
      #  puts "push x #{x} to tail" if DBG
      #elsif conn[p] != x
      #  conn[p,0] = x
      #  puts "push x #{x} to p #{p}" if DBG
      #end
    end
  end
end

for i in 0...n
  print "#{seq[i]} "
end
puts ""

DBG = !true
n,m = gets.split.map{|z| z.to_i}
arcs = Array.new(n).map{[]}
for i in 0...m
  x,y = gets.split.map{|z| z.to_i}
  x -= 1
  y -= 1
  arcs[x] << y
  arcs[y] << x
  #a,b = gets.split
  #a = a.to_i
  #b = b.to_i
end
for i in 0...n
  arcs[i].uniq!
end

if DBG
  print arcs
  puts ""
end

def pushh(h, v)
  if h.empty?
    h << v
    return
  elsif h.size == 1
    if v >= h[0]
      h << v
    else
      h.unshift(v)
    end
    return
  end
  puts "pushh #{v} called" if DBG
  mn = 0
  mx = h.size-1
  if v <= h[0]
    h[0,0] = v if v < h[0]
  elsif  h[mx] <= v
    h << v if h[mx] < v
  else
    while mn+1 < mx
      mid = (mn+mx)/2
      if h[mid] < v
        mn = mid
      else
        mx = mid
      end
    end
    h[mx,0] = v if h[mn] < v && v < h[mx]
  end

end

done = Array.new(n, false)
seq = [1]
done[0] = true
conn = arcs[0].sort
for x in conn
  done[x] = true
end
for i in 1...n
  if DBG
    print "i #{i} conn/done "
    print conn
    print done
    puts ""
  end
  nxt = conn.shift
  puts "picked #{nxt}" if DBG
  #done[nxt] = true
  seq << nxt + 1
  nxcon = arcs[nxt]
  for x in nxcon
    if !done[x]
      done[x] = true
      pushh(conn, x)
      #p = conn.bsearch_index{|z| z>=x}
      #if p.nil?
      #  conn << x
      #  puts "push x #{x} to tail" if DBG
      #elsif conn[p] != x
      #  conn[p,0] = x
      #  puts "push x #{x} to p #{p}" if DBG
      #end
    end
  end
end

for i in 0...n
  print "#{seq[i]} "
end
puts ""


Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide.

Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.

gets
a=gets.split.map &:to_i
x=a.delete 0
puts(if a.size<1
	0
elsif a.size<2
	x ? [a[0],x].max : a[0]
elsif a.count{|_|_<0}%2<1
	a*" "
else
	a.delete_at a.each_with_index.select{|v,i|v<0}.sort[-1][1]
	a*" "
end)

n = gets.chop.to_i
a = gets.chop.split(/ /).map!{|x| x.to_i}
pa = Array.new
ma = Array.new
bzero = false
for i in 0..n-1
	if a[i] == 0
		bzero =  true
	elsif a[i] > 0
		pa.push(a[i])
	else
		ma.push(a[i])
	end
end
ma.sort!{|a,b| a <=> b }
mac = (ma.length / 2)*2
ret = ""
for i in 0..mac-1
	ret << " " if ret.length > 0
	ret << ma[i].to_s
end
for i in 0..pa.length-1
	ret << " " if ret.length > 0
	ret << pa[i].to_s
end

if n == 1
	puts a[0]
elsif ret == "" && bzero
	puts "0"
else
	puts ret
end

n = gets.to_i
costs = gets.split.map { |v| v.to_i }

positive = costs.select { |v| v > 0 }.sort
negative = costs.select { |v| v < 0 }.sort

negative.pop if negative.size.odd?

result = negative + positive
result = Array(costs.max) if result.empty?

puts result.join(' ')

gets
a=gets.split.map &:to_i
a.delete 0
puts(if a.size<1
	0
elsif a.size<2
	a[0]
elsif a.count{|_|_<0}%2<1
	a*" "
else
	a.delete_at a.each_with_index.select{|v,i|v<0}.sort[-1][1]
	a*" "
end)

n = gets.chop.to_i
a = gets.chop.split(/ /).map!{|x| x.to_i}
pa = Array.new
ma = Array.new
bzero = false
for i in 0..n-1
	bzero =  true if a[i] == 0
	if a[i] > 0
		pa.push(a[i])
	else
		ma.push(a[i])
	end
end
ma.sort!{|a,b| b <=> a }
mac = (ma.length / 2)*2
ret = ""
for i in 0..mac-1
	ret << " " if i > 0
	ret << ma[i].to_s
end
for i in 0..pa.length-1
	ret << " " if i > 0
	ret << pa[i].to_s
end

if n == 1
	puts a[0]
elsif ret == "" && bzero
	puts "0"
else
	puts ret
end

n = gets.chop.to_i
a = gets.chop.split(/ /).map!{|x| x.to_i}
pa = Array.new
ma = Array.new
bzero = false
for i in 0..n-1
	bzero =  true if a[i] == 0
	if a[i] > 0
		pa.push(a[i])
	else
		ma.push(a[i])
	end
end
ma.sort!{|a,b| a <=> b }
mac = (ma.length / 2)*2
ret = ""
for i in 0..mac-1
	ret << " " if ret.length > 0
	ret << ma[i].to_s
end
for i in 0..pa.length-1
	ret << " " if ret.length > 0
	ret << pa[i].to_s
end

if n == 1
	puts a[0]
elsif ret == "" && bzero
	puts "0"
else
	puts ret
end

n = gets.chop.to_i
a = gets.chop.split(/ /).map!{|x| x.to_i}
pa = Array.new
ma = Array.new
bzero = false
for i in 0..n-1
	bzero =  true if a[i] == 0
	if a[i] > 0
		pa.push(a[i])
	else
		ma.push(a[i])
	end
end
ma.sort!{|a,b| b <=> a }
mac = (ma.length / 2)*2
ret = ""
for i in 0..mac-1
	ret << " " if i > 0
	ret << ma[i].to_s
end
for i in 0..pa.length-1
	ret << " " if i > 0
	ret << pa[i].to_s
end

if ret == "" && bzero
	puts "0"
else
	puts ret
end


You are given an array $$$A$$$, consisting of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$, and an array $$$B$$$, consisting of $$$m$$$ positive integers $$$b_1, b_2, \dots, b_m$$$. Choose some element $$$a$$$ of $$$A$$$ and some element $$$b$$$ of $$$B$$$ such that $$$a+b$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. For example, if $$$A = [2, 1, 7]$$$ and $$$B = [1, 3, 4]$$$, we can choose $$$1$$$ from $$$A$$$ and $$$4$$$ from $$$B$$$, as number $$$5 = 1 + 4$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. However, we can't choose $$$2$$$ from $$$A$$$ and $$$1$$$ from $$$B$$$, as $$$3 = 2 + 1$$$ belongs to $$$B$$$.It can be shown that such a pair exists. If there are multiple answers, print any.Choose and print any such two numbers.

The first line contains one integer $$$n$$$ ($$$1\le n \le 100$$$) — the number of elements of $$$A$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 200$$$) — the elements of $$$A$$$. The third line contains one integer $$$m$$$ ($$$1\le m \le 100$$$) — the number of elements of $$$B$$$. The fourth line contains $$$m$$$ different integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 200$$$) — the elements of $$$B$$$. It can be shown that the answer always exists.

Output two numbers $$$a$$$ and $$$b$$$ such that $$$a$$$ belongs to $$$A$$$, $$$b$$$ belongs to $$$B$$$, but $$$a+b$$$ doesn't belong to nor $$$A$$$ neither $$$B$$$. If there are multiple answers, print any.

NoteIn the first example, we can choose $$$20$$$ from array $$$[20]$$$ and $$$20$$$ from array $$$[10, 20]$$$. Number $$$40 = 20 + 20$$$ doesn't belong to any of those arrays. However, it is possible to choose $$$10$$$ from the second array too.In the second example, we can choose $$$3$$$ from array $$$[3, 2, 2]$$$ and $$$1$$$ from array $$$[1, 5, 7, 7, 9]$$$. Number $$$4 = 3 + 1$$$ doesn't belong to any of those arrays.In the third example, we can choose $$$1$$$ from array $$$[1, 3, 5, 7]$$$ and $$$1$$$ from array $$$[7, 5, 3, 1]$$$. Number $$$2 = 1 + 1$$$ doesn't belong to any of those arrays.

n = readline.to_i
a = readline.split.map(&:to_i)
m = readline.to_i
b = readline.split.map(&:to_i)

printf "%d %d\n", a.max, b.max

a_size = gets.strip.to_i
a_string = gets.strip

b_size = gets.strip.to_i
b_string = gets.strip

a = a_string.split(' ').map(&:to_i)
b = b_string.split(' ').map(&:to_i)

output = nil

a.each_with_index do |a_element, _a_index|
  b.each_with_index do |b_element, _b_index|
    sum = a_element + b_element
    next if a.include?(sum) || b.include?(sum)

    output = "#{a_element} #{b_element}"
    break
  end

  break unless output.eql?(nil)
end

puts output

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

puts "#{as.max} #{bs.max}"

# coding: utf-8

# if __FILE__ == $0
# end

na = gets.to_i
ar = gets.split.map(&:to_i)
nb = gets.to_i
br = gets.split.map(&:to_i)

catch :found do
    ar.each { |ia|
        br.each { |ib|
            s = ia + ib
            if ar.index(s) == nil && br.index(s) == nil
                puts "#{ia} #{ib}"
                throw :found
            end
        }
    }
end

gets
a = gets.split(' ').map(&:to_i)
gets
b = gets.split(' ').map(&:to_i)
puts a.max.to_s + ' ' + b.max.to_s

n = gets.to_i
aa = gets.split.map(&:to_i).sort
m = gets.to_i
bb = gets.split.map(&:to_i).sort

puts "#{aa.last} #{bb.last}"

n = gets.to_i
a = gets.split.map &:to_i
m = gets.to_i
b = gets.split.map &:to_i
print a.max, ' ', b.max

gets
a = gets.split(' ').map(&:to_i)
gets
b = gets.split(' ').map(&:to_i)
puts a.max + b.max


Given a sequence $$$a_1, a_2, \ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\dots,a_n$$$ ($$$1\leq a_i\leq10^9$$$) — elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.

NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\{[2, 4], [4, 6], [6, 8]\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element.

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  even_count = a.select(&:even?).count
  odd_count = a.count - even_count
  puts [even_count, odd_count].min
end

gets.to_i.times do
n = gets
a = gets.split(' ').map(&:to_i)
puts [a.select{|a|a%2==1}.size, a.select{|a|a%2==0}.size].min
end

gets.to_i.times {
	m = gets.to_i
	n = gets.split.map(&:to_i).count{|a| a.even?}
	p [n, m-n].min
}

def solution(arr)
    odd, even = 0, 0
    arr.each do |e|
        if e % 2 == 0
            even += 1
        else
            odd += 1
        end
    end
    puts odd < even ? odd : even
end

n = $stdin.gets.to_i
(0...n).each do |i|
    size = $stdin.gets.to_i
    arr = $stdin.gets.to_s.split(' ').map(&:to_i)
    solution(arr)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 0
  # prev_idx = 0
  while idx < a.size
    next_id = idx + 1
    # puts "#{prev_idx}-#{idx}-#{a.inspect} - #{k}"
    x = a[idx]
    y = a[next_id]
    break if y.nil?
    sum = x + y

    if sum.even?
      idx += 1
      next
    else
      # if x.even? && y.odd?
        a.delete_at(next_id)

      # elsif y.odd?
      #   a.delete_at(next_id)
        # idx += 1
      # end
      # idx -= 1
      # if a[idx].odd?
        # a.delete_at(idx)
      # end
      k += 1
    end
  end

  puts k

rescue => e
  puts e
  puts a.inspect
  exit(1)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 0
  # prev_idx = 0
  while idx < a.size
    next_id = idx + 1
    # puts "#{prev_idx}-#{idx}-#{a.inspect} - #{k}"
    x = a[idx]
    y = a[next_id]
    break if y.nil?
    sum = x + y

    if sum.even?
      idx += 1
      next
    else
      if x.odd?
        a.delete_at(idx)

      elsif y.odd?
        a.delete_at(next_id)
      end
      # idx -= 1
      # if a[idx].odd?
        # a.delete_at(idx)
      # end
      k += 1
    end
  end

  puts k

rescue => e
  puts e
  puts a.inspect
  exit(1)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 0
  # prev_idx = 0
  while idx < a.size
    next_id = idx + 1
    # puts "#{prev_idx}-#{idx}-#{a.inspect} - #{k}"
    x = a[idx]
    y = a[next_id]
    break if y.nil?
    sum = x + y

    if sum.even?
      idx += 1
      next
    else
      if x.odd?
        a.delete_at(idx)
        # idx -= 1
      elsif y.odd?
        a.delete_at(next_id)
      end

      # if a[idx].odd?
        # a.delete_at(idx)
      # end
      k += 1
    end
  end

  puts k

rescue => e
  puts e
  puts a.inspect
  exit(1)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 1
  while idx < a.size
    prev_idx = idx - 1
    # puts "#{prev_idx}-#{idx}-#{a.size}"
    sum = a[prev_idx] + a[idx]

    if sum.even?
      idx += 1
      next
    else
      # if a[prev_idx].odd?
      #   a.delete_at(prev_idx)
      # elsif a[idx].odd?
      #   a.delete_at(idx)
      # end
      # if a[idx].odd?
        a.delete_at(idx)
      # end
      k += 1
    end
  end

  puts k

# rescue => e
#   puts a.inspect
#   exit(1)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 1
  while idx < a.size
    prev_idx = idx - 1
    # puts "#{prev_idx}-#{idx}-#{a.size}"
    sum = a[prev_idx] + a[idx]

    if sum.even?
      idx += 2
      next
    else
      if a[prev_idx].odd?
        a.delete_at(prev_idx)
      elsif a[idx].odd?
        a.delete_at(idx)
      end
      k += 1
    end
  end

  puts k

# rescue => e
#   puts a.inspect
#   exit(1)
end

t = gets.to_i

(0...t).each do
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  k = 0
  idx = 1
  while idx <= a.size
    prev_idx = idx - 1
    sum = a[prev_idx] + a[idx]

    if sum.even?
      idx += 2
      next
    else
      if a[prev_idx].odd?
        a.delete_at(prev_idx)
      elsif a[idx].odd?
        a.delete_at(idx)
      end
      k += 1
    end
  end

  puts k

rescue => e
  puts e
end


Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \le i \le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.

Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.

NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps.

N = gets.to_i
as = gets.split.map(&:to_i)
ans = 0
while as.length > 0
    a = as.shift
    ans += as.index(a)
    as.delete(a)
end
puts ans

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

sz = ary.size
ans = 0
0.upto(n-1).each do |i|
  ai = i*2
  e = ary[ai]
  eni = ai + 1
  (ai+1).upto(sz-1).each do |j|
    if ary[j] == e
      eni = j
      break
    end
  end
  eni.downto(ai+2).each do |j|
    ary[j] = ary[j-1]
    ary[j-1] = e
    ans += 1
  end
end
puts ans


The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row.Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.

The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300). It is guaranteed that at least one ai is positive.

Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n. As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.

n = gets.to_i
op = Hash.new "PLR"
op[0] = "PRL"
gets.split(' ',n).map(&:to_i).each_with_index do |x,id|
  if id == 0
    print "PRL" * x
  else
    print "R"
    print "PLR" * x
  end
end

=begin
Dear online judge:
I've wasted time reading the problem and trying to figure out the solution
If you insist on the penalty system, please don't include the time of debugging
I hope my code compile and get accepted. KEE O.o
     ____________
    /         __ \
   /   __    |  | \
  /   |__|   |  |  \
 (           |__|   )
  \                /
   \      ___     /
    \____________/
=end

class Solve
  def solve()
    $n = Integer(gets)
    $list = gets().split()
    $count = 0
    $n -= 1
    for $i in 0..$n do
      if $list[$i] != "0"
        $count += Integer($list[$i])
      end
    end
    $res = ""
    $dir = 1
    $i = 0
    $cur = Array.new($n + 1,0)
    while $count > 0 do
      if $cur[$i] < Integer($list[$i])
        $cur[$i] += 1
        $count -= 1
        $res<<'P'
      end
      if $count > 0
        if $i == $n
          $dir = -1
        else
          if $i == 0
            $dir = 1
          end
        end
        if $dir == 1
          $res<<'R'
        end
        if $dir == -1
          $res<<'L'
        end
      end
      $i += $dir
    end
    puts $res
  end
end

Solve.new.solve

RIGHT = 1
LEFT  = 0

wallets_count, *wallets = STDIN.read.split

wallets.map!(&:to_i)
wallets_count = wallets_count.to_i

index         = 0
direction     = RIGHT
coins_to_give = wallets.inject(0) { |sum, value| sum + value }

until coins_to_give.zero?
  if wallets[index] > 0
    print :P
    wallets[index] -= 1
    coins_to_give  -= 1
    break if coins_to_give.zero?
  end

  if (direction == RIGHT && index < wallets_count - 1) || (direction == LEFT && index == 0)
    print :R
    index += 1
    direction = RIGHT
  else
    print :L
    index -= 1
    direction = LEFT
  end
end

print "\n"

inA = gets
inB = gets
count = inA.to_i

counts = inB.split
counts.map! {|x| x.to_i}

result = ""
position = 0
forward = true
lastPuted = 0
while true
	if(counts[position] > 0)
		result << 'P'
		lastPuted = 0
		counts[position] -= 1
	else
		lastPuted += 1
	end

	if(forward && (position == counts.length() -1))
		forward = false
	elsif ( (!forward) && position == 0)
		forward = true
	end

	if(forward)
		position += 1
		result << 'R'
	else
		position -= 1
		result << 'L'
	end

	if(lastPuted > (counts.length*2 + 2))
		puts result.slice(0, result.length - lastPuted - 1)
		break
	end
end

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "P"
else
    sov[0] = nil
end
b = Array.new
for i in  1...n
    if a[i] >= 1
        b[i] = "RPL" * (a[i]-1) + "RP"
    else  a[i] == 0
        b[i] = "R"
    end

    sov.push(b[i])
end
print sov.join

n=gets.to_i
d=gets.split.map(&:to_i)
ans=''
n.times do |i|
    if i == 0
        ans+= 'RLP'*d[i]
    else
        ans+= 'LRP'*d[i]
    end
    ans+='R'
end
puts ans[0..-2]

n=gets.to_i
a=gets.split.map(&:to_i)
print 'PRL'*a[0]
(1..n-1).each{|i|print 'R','PLR'*a[i]}

n=gets.to_i
a=gets.split.map(&:to_i)
x=0
s=''
loop do
  (a[x]-=1;s<<'P')if a[x]>0
  if x==0
    x+=1
    s<<'R'
  elsif a[x-1]>0 || a[x]>0
    x-=1
    s<<'L'
  elsif x==n-1
    if a[x]>0
      x-=1
      s<<'L'
    else
      break
    end
  elsif
    x+=1
    s<<'R'
  end
end
puts s

n = gets.to_i
a = gets.split.map(&:to_i)
print 'PRL' * a[0]
c = false
if a[n-1] != 0
a[n-1] -= 1
c = true
end
(1..n-1).each{|i| print 'R', 'PLR' * a[i]}
if c
print 'P'
end

n = gets.to_i
a = gets.split.map(&:to_i)
print 'PRL' * a[0]
(1..n-1).each{|i| print 'R', 'PLR' * a[i]}

inA = gets
inB = gets
count = inA.to_i

counts = inB.split
counts.map! {|x| x.to_i}

result = ""
position = 0
forward = true
lastPuted = 0
while true
	if(counts[position] > 0)
		result << 'P'
		lastPuted = 0
		counts[position] -= 1
	else
		lastPuted += 1
	end

	if(forward && (position == counts.length() -1))
		forward = false
	elsif ( (!forward) && position == 0)
		forward = true
	end

	if(forward)
		position += 1
		result << 'R'
	else
		position -= 1
		result << 'L'
	end

	if(lastPuted > counts.length)
		puts result.slice(0, result.length - lastPuted - 1)
		break
	end
end

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "PR"
else
    sov[0] = nil
end
b = Array.new
for i in  1...n
    b[i] = ("R" * i + "P"  + "L" * i) * a[i]
    sov.push(b[i])
end
print sov.join

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "PR"
else
    sov[0] = nil
end
b = Array.new
for i in  1...n
    if a[i] >= 2
        b[i] = "PL" + "RPL" * (a[i]-2) + "RP"
    else a[i] = 1
        b[i] = "PL"
    end

    sov.push(b[i])
end
print sov.join

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "PR"
else
    sov[0] = "R"
end
b = Array.new
for i in  1...n
    if a[i] >= 2
        b[i] = "PL" + "RPL" * (a[i]-2) + "RP"
    elsif a[i] == 1
        b[i] = "PL"
    else  a[i] == 0
        b[i] = "R"
    end

    sov.push(b[i])
end
print sov.join

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
sov[0] = "PRL" * a[0]
b = Array.new
for i in  1...n
    b[i] = ("R" * i + "P"  + "L" * i) * a[i]
    sov.push(b[i])
end
print sov.join

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "PR"
else
    sov[0] = "R"
end
b = Array.new
for i in  1...n
    if a[i] >= 2
        b[i] = "PL" + "RPL" * (a[i]-2) + "RP"
    elsif a[i] == 1
        b[i] = "PL"
    else  a[i] == 0
        b[i] = "RR"
    end

    sov.push(b[i])
end
print sov.join

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
sov = Array.new
if a[0] != 0
    sov[0] = "PRL" * (a[0]-1) + "PR"
else
    sov[0] = "R"
end
b = Array.new
for i in  1...n
    if a[i] >= 2
        b[i] = "PL" + "RPL" * (a[i]-2) + "RP"
    else a[i] = 1
        b[i] = "PL"
    end

    sov.push(b[i])
end
print sov.join

n = gets.to_i
a = gets.split.map(&:to_i)
print 'PRL' * a[0]
if a[n-1] != 0
a[n-1] -= 1
end
(1..n-1).each{|i| print 'R', 'PLR' * a[i]}
print 'P'


One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height / width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.

The first line contains a pair of integers h and w (1 ≤ h, w ≤ 109) which are the height and width of the uploaded photo in pixels.

Print two integers which are the height and width of the cut area.

def solve(x, y)
  m = Math.log2(x).to_i
  n = Math.log2(y).to_i
  if n == m
    return 2 ** n, [y, (1.25*2**n).to_i].min
  elsif n == m + 1
    if x > (2 ** n / 1.25).to_i
      return (2 ** n / 1.25).to_i, 2 ** n
    else
      return 2 ** m, (1.25 * 2 ** m).to_i
    end
  else
    return 2 ** m, (1.25 * 2 ** m).to_i
  end
end

y, x = gets.split.map(&:to_i)
x0, y0 = x, y
swap = false
if x > y
  x, y = y, x
  swap = true
end

p, q = solve(x, y)
if swap
  p, q = q, p
end
if p > q and (p <= y0 and q <= x0)
  p, q = q, p
end
printf("%d %d\n", q, p)

def solve(x, y)
  m = Math.log2(x).to_i
  n = Math.log2(y).to_i
  if n == m
    return 2 ** n, [y, (1.25*2**n).to_i].min
  elsif n == m + 1
    if x > (2 ** n / 1.25).to_i
      return (2 ** n / 1.25).to_i, 2 ** n
    else
      return 2 ** m, (1.25 * 2 ** m).to_i
    end
  else
    return 2 ** m, (1.25 * 2 ** m).to_i
  end
end

y, x = gets.split.map(&:to_i)
swap = false
if x > y
  x, y = y, x
  swap = true
end

p, q = solve(x, y)
if swap
  p, q = q, p
end
printf("%d %d\n", q, p)

def solve(x, y)
  m = Math.log2(x).to_i
  n = Math.log2(y).to_i
  if n == m
    return 2 ** n, [y, (1.25*x).to_i].min
  elsif n == m + 1
    if x > (2 ** n / 1.25).to_i
      return (2 ** n / 1.25).to_i, 2 ** n
    else
      return 2 ** m, (1.25 * 2 ** m).to_i
    end
  else
    return 2 ** m, (1.25 * 2 ** m).to_i
  end
end

y, x = gets.split.map(&:to_i)
swap = false
if x > y
  x, y = y, x
  swap = true
end

p, q = solve(x, y)
if swap
  p, q = q, p
end
printf("%d %d\n", q, p)