Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square. Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.

The first line of the input contains number n — the number of mines on the map (2 ≤ n ≤ 1000). Each of the next n lines contains a pair of integers xi and yi — the coordinates of the corresponding mine ( - 109 ≤ xi, yi ≤ 109). All points are pairwise distinct.

Print the minimum area of the city that can cover all the mines with valuable resources.

n = STDIN.readline.to_i
x_min, y_min = 10**10, 10**10
x_max, y_max = -x_min, -y_min
n.times do
	x, y = STDIN.readline.split.map {|s| s.to_i }
	x_min = x if x < x_min
	y_min = y if y < y_min
	x_max = x if x > x_max
	y_max = y if y > y_max
end
a, b = x_max-x_min, y_max-y_min
puts [a, b].max**2

n= gets.to_i
mx, my, lx, ly = -1.0/0.0, -1.0/0.0, 1.0/0.0, 1.0/0.0
n.times do
  x,y = gets.split.map(&:to_i)
  mx = [mx,x].max
  my = [my,y].max
  lx = [lx,x].min
  ly = [ly,y].min
end
puts [mx-lx,my-ly].max**2

data = gets.to_i.times.map{gets.split.map{|x|x.to_i}}
min_x = data.map{|x|x[0]}.min
max_x = data.map{|x|x[0]}.max
min_y = data.map{|x|x[1]}.min
max_y = data.map{|x|x[1]}.max
result = [(max_x - min_x), (max_y - min_y)].max**2
puts result

# 485B

min_x = min_y = 10 ** 9 + 1
max_x = max_y = -min_x
gets.to_i.times do
  x, y = gets.chomp.split.map &:to_i
  if x < min_x
    min_x = x
  end
  if x > max_x
    max_x = x
  end
  if y < min_y
    min_y = y
  end
  if y > max_y
    max_y = y
  end
end
puts [max_x - min_x, max_y - min_y].max ** 2

n = gets.to_i
maxX = -10 ** 9
maxY = -10 ** 9
minX = 10 ** 9
minY = 10 ** 9
n.times do
	input = gets
	x_coor = input.split[0].to_i
	y_coor = input.split[1].to_i
	if x_coor > maxX
		maxX = x_coor
	end
	if y_coor > maxY
		maxY = y_coor
	end
	if x_coor < minX
		minX = x_coor
	end
	if y_coor < minY
		minY = y_coor
	end
end
x = maxX - minX
y = maxY - minY
puts x > y ? x ** 2 : y ** 2

INF = 2e10;

def max(a, b)
  a > b ? a : b
end

def min(a, b)
  a < b ? a : b
end

n = gets.chomp.to_i
top = -INF
bottom = INF
right = -INF
left = INF

n.times do
  p = gets.chomp.split(" ").map{|str|str.to_i}

  top = max(top, p[1])
  bottom = min(bottom, p[1])
  right = max(right, p[0])
  left = min(left, p[0])
end

width = right - left
height = top - bottom

puts max(width, height) ** 2

n = STDIN.readline.to_i
x_min, y_min = 10**10, 10**10
x_max, y_max = -x_min, -y_min
n.times do
	x, y = STDIN.readline.split.map {|s| s.to_i }
	x_min = x if x < x_min
	y_min = y if y < y_min
	x_max = x if x > x_min
	y_max = y if y > y_min
end
a, b = x_max-x_min, y_max-y_min
puts [a, b].max**2

n= gets.to_i
mx,my,lx,ly=0,0,0,0
n.times do
  x,y = gets.split.map(&:to_i)
  mx = [mx,x].max
  my = [my,y].max
  lx = [lx,x].min
  ly = [ly,y].min
end
puts [mx-lx,my-ly].max**2

data = gets.to_i.times.map{gets.split.map{|x|x.to_i}}
min_x = data.min{|row| row[0]}[0]
max_x = data.max{|row| row[0]}[0]
min_y = data.min{|row| row[1]}[1]
max_y = data.max{|row| row[1]}[1]
result = [(max_x - min_x), (max_y - min_y)].max**2
puts result

def get_task_data(filename)
  raw_data = open(filename){|f|f.readlines}
  count = raw_data[0].to_i
  return false if count.zero?
  data = raw_data[1,raw_data.size].map{|str|str.split.map{|digit| digit.to_i}}
  return false if data.select{|row| row.size!=2}.any?
  return data.size==count ? data : false
end

def solve(filename)
  task_data = get_task_data filename
  return 0 unless task_data
  min_x = task_data.min{|row| row[0]}[0]
  max_x = task_data.max{|row| row[0]}[0]
  min_y = task_data.min{|row| row[1]}[1]
  max_y = task_data.max{|row| row[1]}[1]
  [(max_x - min_x), (max_y - min_y)].max**2
end

data = gets.to_i.times.map{gets.split.map{|x|x.to_i}}
puts data
min_x = data.map{|x|x[0]}.min
max_x = data.map{|x|x[0]}.max
min_y = data.map{|x|x[1]}.min
max_y = data.map{|x|x[1]}.max
puts "min_x:#{min_x} max_x:#{max_x} min_y:#{min_y} max_y:#{max_y}"
result = [(max_x - min_x), (max_y - min_y)].max**2
puts result

# 485B

min_x = min_y = 10 ** 9 + 1
max_x = max_y = -min_x
gets.to_i.times do
  x, y = gets.chomp.split.map &:to_i
  if x < min_x
    min_x = x
  elsif x > max_x
    max_x = x
  end
  if y < min_y
    min_y = y
  elsif y > max_y
    max_y = y
  end
end
puts [max_x - min_x, max_y - min_y].max ** 2

# 485B

min_x = min_y = 10 ** 9 + 1
max_x = max_y = -min_x
gets.to_i.times do
  x, y = gets.chomp.split.map &:to_i
  if x < min_x
    min_x = x
  end
  if x > max_x
    max_x = x
  end
  if y < min_y
    min_y = y
  end
  if y > max_y
    max_y = y
  end
end
p [min_x, max_x, min_y, max_y]
puts [max_x - min_x, max_y - min_y].max ** 2

n = gets.to_i
maxX = -10 ** 9
maxY = -10 ** 9
minX = 10 ** 9
minY = 10 ** 9
n.times do
	input = gets
	x_coor = input.split[0].to_i
	y_coor = input.split[1].to_i
	if x_coor > maxX
		max = x_coor
	end
	if y_coor > maxY
		maxY = y_coor
	end
	if x_coor < minX
		minX = x_coor
	end
	if y_coor < minY
		minY = y_coor
	end
end
x = maxX - minX
y = maxY - minY
puts x > y ? x ** 2 : y ** 2

n = gets.to_i
max = -10 ** 9
min = 10 ** 9
n.times do
	input = gets
	x_coor = input.split[0].to_i
	y_coor = input.split[1].to_i
	if x_coor > max
		max = x_coor
	elsif y_coor > max
		max = y_coor
	end
	if x_coor < min
		min = x_coor
	elsif y_coor < min
		min = y_coor
	end
end

puts (max - min) ** 2

n = gets.to_i
max = 0
n.times do
	input = gets
	x_coor = input.split[0].to_i
	y_coor = input.split[1].to_i
	if x_coor > max
		max = x_coor
	elsif y_coor > max
		max = y_coor
	end
end

puts max ** 2

n = gets.to_i
maxX = -10 ** 9
maxY = -10 ** 9
minX = 10 ** 9
minY = -10 ** 9
n.times do
	input = gets
	x_coor = input.split[0].to_i
	y_coor = input.split[1].to_i
	if x_coor > maxX
		max = x_coor
	end
	if y_coor > maxY
		maxY = y_coor
	end
	if x_coor < minX
		minX = x_coor
	end
	if y_coor < minY
		minY = y_coor
	end
end
x = maxX - minX
y = maxY - minY
puts x > y ? x ** 2 : y ** 2


Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!

The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree.

Print one integer – the number of lifelines in the tree.

NoteIn the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.

nodes = gets.to_i
edges = nodes-1
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

puts g.reduce(0) { |res, (n, nxts)|
  res + nxts.size * (nxts.size - 1) / 2
}


Consider the set of all nonnegative integers: $$${0, 1, 2, \dots}$$$. Given two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$). We paint all the numbers in increasing number first we paint $$$0$$$, then we paint $$$1$$$, then $$$2$$$ and so on.Each number is painted white or black. We paint a number $$$i$$$ according to the following rules:    if $$$i = 0$$$, it is colored white;   if $$$i \ge a$$$ and $$$i - a$$$ is colored white, $$$i$$$ is also colored white;   if $$$i \ge b$$$ and $$$i - b$$$ is colored white, $$$i$$$ is also colored white;   if $$$i$$$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if $$$a=3$$$, $$$b=5$$$, then the colors of the numbers (in the order from $$$0$$$) are: white ($$$0$$$), black ($$$1$$$), black ($$$2$$$), white ($$$3$$$), black ($$$4$$$), white ($$$5$$$), white ($$$6$$$), black ($$$7$$$), white ($$$8$$$), white ($$$9$$$), ...Note that:    It is possible that there are infinitely many nonnegative integers colored black. For example, if $$$a = 10$$$ and $$$b = 10$$$, then only $$$0, 10, 20, 30$$$ and any other nonnegative integers that end in $$$0$$$ when written in base 10 are white. The other integers are colored black.   It is also possible that there are only finitely many nonnegative integers colored black. For example, when $$$a = 1$$$ and $$$b = 10$$$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ lines follow, each line contains two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$).

For each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all valid answers).

def solve(a, b)
  a.gcd(b) == 1 ? "Finite" : "Infinite"
end

gets.strip.to_i.times do
  puts solve(*gets.strip.split(' ').map(&:to_i))
end

number_of_tests = gets.chomp.to_i

number_of_tests.times do
  a, b = gets.chomp.split.map(&:to_i)
  puts a.gcd(b) == 1 ? 'Finite' : 'Infinite'
end


PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $$$6$$$ slices, medium ones consist of $$$8$$$ slices, and large pizzas consist of $$$10$$$ slices each. Baking them takes $$$15$$$, $$$20$$$ and $$$25$$$ minutes, respectively.Petya's birthday is today, and $$$n$$$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $$$n$$$ slices in total. For example:   if $$$12$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$12$$$ slices in total. He can order two small pizzas, containing exactly $$$12$$$ slices, and the time to bake them is $$$30$$$ minutes;  if $$$15$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$15$$$ slices in total. He can order a small pizza and a large pizza, containing $$$16$$$ slices, and the time to bake them is $$$40$$$ minutes;  if $$$300$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$300$$$ slices in total. He can order $$$15$$$ small pizzas, $$$10$$$ medium pizzas and $$$13$$$ large pizzas, in total they contain $$$15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300$$$ slices, and the total time to bake them is $$$15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750$$$ minutes;  if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $$$15$$$ minutes.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each testcase consists of a single line that contains a single integer $$$n$$$ ($$$1 \le n \le 10^{16}$$$) — the number of Petya's friends.

For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least $$$n$$$ slices in total.

/Variables:/
friends = 0
total_time = []
testcases = 0

/Prerequisites: Enter de numer of testcases/
testcases = Integer(gets.chomp)

/Firts: Request the number of friends to come/
for i in (0..(testcases-1))
    friends = Integer(gets.chomp)

    if friends <= 6
        friends = 6
    end
    if (friends%2)!=0
        friends = friends + 1
    end
    total_time[i] = (5*friends)/2
end
total_time.each do |elements|
    puts (elements)
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def solve
  puts [((gi + 1) / 2) * 5 , 15].max
end

def main
  gi.times { solve }
end

main

gets
$stdin.map(&:to_i).each do |n|
  puts [(n + 1) / 2 * 5, 15].max
end

/
Problem: Petya wants to order pizza for her birthday.
She does not know how much of her friends will come and
she wants to order so much pizza that each of his friends gets at least one slice of pizza.
The cooking time of the order is the total baking time of all the pizzas in the order.
Input
The first line contains a single integer t (1≤t≤104) — the number of testcases.
Each testcase consists of a single line that contains a single integer n (1≤n≤1016) — the number of Petya's friends.
Output
For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least n slices in total.
/
/Solution:/
/Declare the variables necessaries./
/Constants:/
SMALL_PIZZA = 6
MEDIUM_PIZZA = 8
LONG_PIZZA = 10
TIME_SMALL_PIZZA = 15
TIME_MEDIUM_PIZZA = 20
TIME_LONG_PIZZA = 25

/Variables:/
friends = 0
small_pizza_order = 1
medium_pizza_order = 0
long_pizza_order = 0
total_time = 0

condition = true
limit_small_pizza = false
limit_medium_pizza = false
limit_long_pizza = false

/Firts: Request the number of friends to come/
friends = Integer(gets.chomp)

/Second: Determinate the number of pizzas to order/
/In order to translate de minimun slides at one for friends, when it is one more slide than the number of friends, /
/it does not matter, because satisfate the condicion of minimun slides for person./
/So, for friends equals or less than 6, the case just be order a small pizza/

if friends <= 6
    /Case for small pizza:/
    small_pizza_order = 1
else
    /Other case/
    /We must to do a loop until aprox our value to the number of friends/
    while condition
        /For the max number of small pizza/
        if !limit_small_pizza
            /Sum one more pizza/
            small_pizza_order = small_pizza_order + 1
            /Quest if the number of slides is equals than the number of friends/
            if SMALL_PIZZA*small_pizza_order == friends || (SMALL_PIZZA*small_pizza_order) == (friends +1)
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif SMALL_PIZZA*small_pizza_order > friends
                small_pizza_order = small_pizza_order - 2
                limit_small_pizza = true
            /Other case slides is small than friends and continue/
            end

        /For the max number of medium pizza/
        elsif !limit_medium_pizza
            /Sum one more pizza/
            medium_pizza_order = medium_pizza_order + 1
            /Quest if the number of slides is equals than the number of friends/
            if (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) == friends || (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) == (friends +1) || ((SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order)-1) == friends
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) > friends
                medium_pizza_order = medium_pizza_order - 2
                limit_medium_pizza = true
            /Other case slides is medium than friends and continue/
            end

        /For the max number of large pizza/
        elsif !limit_long_pizza
            /Sum one more pizza/
            long_pizza_order = long_pizza_order + 1
            /Quest if the number of slides is equals than the number of friends/
            if (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) == friends || (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) == (friends +1) || ((SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order)-1) == friends
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) > friends
                long_pizza_order = long_pizza_order - 1
                limit_long_pizza = true
                condition = false
            /Other case slides is large than friends and continue/
            end
        end
    end
end
total_time = TIME_SMALL_PIZZA*small_pizza_order + TIME_MEDIUM_PIZZA*medium_pizza_order + TIME_LONG_PIZZA*long_pizza_order
puts(total_time)

/
Problem: Petya wants to order pizza for her birthday.
She does not know how much of her friends will come and
she wants to order so much pizza that each of his friends gets at least one slice of pizza.
The cooking time of the order is the total baking time of all the pizzas in the order.
Input
The first line contains a single integer t (1≤t≤104) — the number of testcases.
Each testcase consists of a single line that contains a single integer n (1≤n≤1016) — the number of Petya's friends.
Output
For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least n slices in total.
/
/Solution:/
/Declare the variables necessaries./
/Constants:/
SMALL_PIZZA = 6
MEDIUM_PIZZA = 8
LONG_PIZZA = 10
TIME_SMALL_PIZZA = 15
TIME_MEDIUM_PIZZA = 20
TIME_LONG_PIZZA = 25

/Variables:/
friends = 0
small_pizza_order = 1
medium_pizza_order = 0
long_pizza_order = 0
total_time = 0

condition = true
limit_small_pizza = false
limit_medium_pizza = false
limit_long_pizza = false

/Firts: Request the number of friends to come/
puts("Enter the number of friends that will come to Petya party")
friends = Integer(gets.chomp)

/Second: Determinate the number of pizzas to order/
/In order to translate de minimun slides at one for friends, when it is one more slide than the number of friends, /
/it does not matter, because satisfate the condicion of minimun slides for person./
/So, for friends equals or less than 6, the case just be order a small pizza/

if friends <= 6
    /Case for small pizza:/
    small_pizza_order = 1
else
    /Other case/
    /We must to do a loop until aprox our value to the number of friends/
    while condition
        /For the max number of small pizza/
        if !limit_small_pizza
            /Sum one more pizza/
            small_pizza_order = small_pizza_order + 1
            /Quest if the number of slides is equals than the number of friends/
            if SMALL_PIZZA*small_pizza_order == friends || (SMALL_PIZZA*small_pizza_order) == (friends +1)
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif SMALL_PIZZA*small_pizza_order > friends
                small_pizza_order = small_pizza_order - 2
                limit_small_pizza = true
            /Other case slides is small than friends and continue/
            end

        /For the max number of medium pizza/
        elsif !limit_medium_pizza
            /Sum one more pizza/
            medium_pizza_order = medium_pizza_order + 1
            /Quest if the number of slides is equals than the number of friends/
            if (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) == friends || (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) == (friends +1) || ((SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order)-1) == friends
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order) > friends
                medium_pizza_order = medium_pizza_order - 2
                limit_medium_pizza = true
            /Other case slides is medium than friends and continue/
            end

        /For the max number of large pizza/
        elsif !limit_long_pizza
            /Sum one more pizza/
            long_pizza_order = long_pizza_order + 1
            puts(long_pizza_order)
            /Quest if the number of slides is equals than the number of friends/
            if (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) == friends || (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) == (friends +1) || ((SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order)-1) == friends
                limit_small_pizza = true
                limit_medium_pizza = true
                limit_long_pizza = true
                condition = false
            /Quest if is more than the number of friends/
            elsif (SMALL_PIZZA*small_pizza_order + MEDIUM_PIZZA*medium_pizza_order + LONG_PIZZA*long_pizza_order) > friends
                long_pizza_order = long_pizza_order - 1
                limit_long_pizza = true
                condition = false
            /Other case slides is large than friends and continue/
            end
        end
    end
end
total_time = TIME_SMALL_PIZZA*small_pizza_order + TIME_MEDIUM_PIZZA*medium_pizza_order + TIME_LONG_PIZZA*long_pizza_order
puts(total_time)


Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.

Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.

For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way:  At $$$0$$$-th minute, change the state to heating (the temperature is 0).  At $$$2$$$-nd minute, change the state to off (the temperature is 2).  At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied).  At $$$6$$$-th minute, change the state to off (the temperature is 3).  At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied).  At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

# frozen_string_literal: true

@data = $stdin.read.split

def next_token
  @data.shift
end

def next_int
  next_token.to_i
end

def solve(n, m, t, l, r)
  low = m
  high = m
  last_t = 0
  n.times do |i|
    d = (t[i] - last_t)
    low -= d
    high += d
    low = l[i] if low < l[i]
    high = r[i] if high > r[i]
    return false if low > high

    last_t = t[i]
  end
  true
end

T = next_int
t = Array.new(100)
l = Array.new(100)
r = Array.new(100)

T.times do
  n = next_int
  m = next_int
  n.times do |i|
    t[i] = next_int
    l[i] = next_int
    r[i] = next_int
  end
  puts solve(n, m, t, l, r) ? 'YES' : 'NO'
end


Polycarp is a great fan of television.He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.Polycarp wants to check out all n shows. Are two TVs enough to do so?

The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of shows. Each of the next n lines contains two integers li and ri (0 ≤ li < ri ≤ 109) — starting and ending time of i-th show.

If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).

l, c = [], 0
gets.to_i.times do
  a, b = gets.split.map(&:to_f)
  l.push(a)
  l.push(b + 0.5)
end
l.sort!.each do |a|
  if a % 1 == 0
    c += 1
    break if c > 2
  else
    c -= 1
  end
end
puts c > 2 ? :NO : :YES

n = gets.to_i
shows = []
n.times do
  shows.push(gets.split.map(&:to_i))
end
shows.sort_by! { |start, _| start }

buffer = []
shows.each do |start, ending|
  buffer = buffer.select { |show| show[1] >= start } + [[start, ending]]
  break if buffer.count > 2
end
puts buffer.count > 2 ? "NO" : "YES"


This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.

The first line of the input contains two positive integers n and k (1 ≤ n, k ≤ 1000) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.

n, k = readline.split(' ').collect(&:to_i)
a = readline.split(' ').collect(&:to_i)
b = readline.split(' ').collect(&:to_i)
down = 0
up = (b[0] + k) / a[0] + 1
while down + 1 < up
  mid = (down + up) / 2
  need = 0
  a.zip(b).each do |aa, bb|
    if aa * mid > bb
      need += aa * mid - bb
    end
  end
  if need <= k
    down = mid
  else
    up = mid
  end
end
puts down

input = gets.chomp.split(' ').map { |i| i.to_i }
ingredientNum, magicPowderNum = input[0], input[1]

input = gets.chomp.split(' ').map { |i| i.to_i }
needed = []

input.each do |item|
	needed << item
end

input = gets.chomp.split(' ').map { |i| i.to_i }
have = []

input.each do |item|
	have << item
end

nowMade = []

for i in (0...ingredientNum)
	nowMade << ((have[i] / needed[i]).floor)
end

=begin
nowMade.each do |i|
	puts "nowMade : #{i}"
end
=end

min = 0

until magicPowderNum <= 0
	min = nowMade.sort[0]
#	puts "min : #{min}"

	idx = nowMade.find_index { |i| i == min }

#	puts "idx : #{idx}"
	subVal = (needed[idx] - (have[idx] % needed[idx]))
	magicPowderNum -= subVal

	break if magicPowderNum < 0
	have[idx] += subVal
	nowMade[idx] += 1

#	puts "Remained : #{magicPowderNum}"
end

min = nowMade.sort[0]
puts min

parse_int = lambda { gets.split.map{|x| x.to_i} }

n, magic = parse_int.call
for_one = parse_int.call
havin = parse_int.call

cookies = 0

while true

  #puts havin.to_s
  #puts magic
  #puts

  n.times{ |_|
    havin[_] -= for_one[_]
    if havin[_] < 0
      magic += havin[_]
      havin[_] = 0
    end
  }
  break if magic < 0
  cookies += 1
end

print cookies


You are given integer $$$n$$$. You have to arrange numbers from $$$1$$$ to $$$2n$$$, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every $$$n$$$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $$$2n$$$ numbers differ not more than by $$$1$$$.For example, choose $$$n = 3$$$. On the left you can see an example of a valid arrangement: $$$1 + 4 + 5 = 10$$$, $$$4 + 5 + 2 = 11$$$, $$$5 + 2 + 3 = 10$$$, $$$2 + 3 + 6 = 11$$$, $$$3 + 6 + 1 = 10$$$, $$$6 + 1 + 4 = 11$$$, any two numbers differ by at most $$$1$$$. On the right you can see an invalid arrangement: for example, $$$5 + 1 + 6 = 12$$$, and $$$3 + 2 + 4 = 9$$$, $$$9$$$ and $$$12$$$ differ more than by $$$1$$$.

The first and the only line contain one integer $$$n$$$ ($$$1 \le n \le 10^5$$$).

If there is no solution, output "NO" in the first line.  If there is a solution, output "YES" in the first line. In the second line output $$$2n$$$ numbers — numbers from $$$1$$$ to $$$2n$$$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.

NoteExample from the statement is shown for the first example. It can be proved that there is no solution in the second example.

n = gets.to_i
if n%2 == 0
  puts 'NO'
else
  puts 'YES'
  a = []
  (1..n).each do |x|
    if x%2 != 0
      a[x - 1] = 2*x - 1
      a[x - 1 + n] = 2*x
    else
      a[x - 1] = 2*x
      a[x - 1 + n] = 2*x - 1
    end
  end
  a.each {|x| print x, ' '}
end

n = gets.to_i
if n%2==0
  puts "NO"
  exit
end
ans = []

# 以下で1から順番に入れる。
#1から反対側に飛ぶ。{右隣に1つ移動。反対側に飛ぶ}を繰り返す
ans[0] = 1
side_a = 0
side_b = n
2.step(n*2,2).with_index do |num, i|
  if i%2==0
    ans[side_b + i] = num
    ans[side_b+1 + i] = num+1
  else
    ans[side_a + i]= num
    ans[side_a+1 + i]= num+1
  end
end
puts "YES\n#{ans[0..(2*n-1)].join(' ')}"


You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \ge 1$$$ you can choose:   either $$$a_i = a_{i - 1} + x$$$  or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \le B$$$ for all $$$i$$$ and $$$\sum\limits_{i=0}^{n}{a_i}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le B, x, y \le 10^9$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the maximum possible $$$\sum\limits_{i=0}^{n}{a_i}$$$.

NoteIn the first test case, the optimal sequence $$$a$$$ is $$$[0, 1, 2, 3, 4, 5]$$$.In the second test case, the optimal sequence $$$a$$$ is $$$[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$$$.In the third test case, the optimal sequence $$$a$$$ is $$$[0, -3, -6, 1, -2]$$$.

gets.to_i.times do
  n, b, x, y = gets.split.map(&:to_i)
  a, sum = 0, 0
  n.times do
    if a + x <= b
      a += x
    else
      a -= y
    end
    sum += a
  end
  p sum
end

gets.to_i.times do
  n, b, x, y = gets.split.map(&:to_i)
  a, sum = 0, 0
  n.times do
    if a + x <= b && a + x - y <= b
      a += x
    else
      a -= y
    end
    sum += a
  end
  p sum
end

main = -> {
  t = int
  t.times do
      n, b, x, y = ints
      sum = 0
      cur = 0
      n.times do
          if cur + x <= b
              cur += x
          else
              cur -= y
          end
          sum += cur
      end
      puts sum
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]


Pasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least common multiple (LCM) of the number of mushrooms on these lawns. But one day Pasha and Akim had an argument about the laughy mushrooms and tore the map. Pasha was left with just some part of it, containing only m roads. Your task is to help Pasha — use the map he has to restore the number of mushrooms on every lawn. As the result is not necessarily unique, help Pasha to restore any one or report that such arrangement of mushrooms does not exist. It is guaranteed that the numbers on the roads on the initial map were no less that 1 and did not exceed 106.

The first line contains two numbers n and m () which are the numbers of lawns and roads we know about. Each of the following m lines contains four numbers which are the numbers of lawns the road connects, the GCD and the LCM of the numbers of mushrooms on these lawns (1 ≤ GCD, LCM ≤ 106). It is guaranteed, that no road connects lawn to itself, and no two lawns are connected by more than one road.

The answer should contain "YES" or "NO" on the first line, saying whether it is possible or not to perform the arrangement. If the answer is "YES", print on the following line n numbers which are the numbers of mushrooms on the corresponding lawns.

def candidates(a, b)
  return nil if b%a != 0
  ret = []
  i = a
  while true
    if b%i == 0
      ret << i
    end
    i += a
    break if i > b
  end

  ret.sort.uniq
end

def do_assign(rules, idx, v, assign)
  assign[idx] = v
  rules.each do |i,j,a,b|
    if i == idx
      return nil if a*b%v != 0
      o = a*b/v
      return nil if v.gcd(o) != a
      assign[j] ||= o
      return nil if assign[j] != o
    end

    if j == idx
      return nil if a*b%v != 0
      o = a*b/v
      return nil if v.gcd(o) != a
      assign[i] ||= o
      return nil if assign[i] != o
    end
  end

  return true
end

def do_it(rules, cd, i, assign={})
  return assign if i > cd.keys.max

  i += 1 until cd[i]

  cd[i].each do |a|
    assign2 = assign.dup
    ret = do_assign(rules, i, a, assign2)
    if ret
      ret2 = do_it(rules, cd, i+1, assign2)
      return ret2 if ret2
    end
  end

  return nil
end

def hoge(data)
  return {} if data.empty?

  gg = {}
  ll = {}

  data.each do |i,j,a,b|
    ll[i] ||= b
    ll[j] ||= b

    ll[i] = ll[i].gcd(b)
    ll[j] = ll[j].gcd(b)

    gg[i] ||= a
    gg[j] ||= a

    gg[i] = gg[i]*a/gg[i].gcd(a)
    gg[j] = gg[j]*a/gg[j].gcd(a)
  end

  cd = {}
  gg.keys.each do |i|
    cd[i] = candidates(gg[i], ll[i])
    return nil unless cd[i]
  end

  ret = do_it(data, cd, 0, {})
end

n, m = gets.split.map(&:to_i)
data = []
m.times do
  data << gets.split.map(&:to_i)
end

ret = hoge(data)
if ret
  puts "YES"
  o = []
  1.upto(n){|i| o << (ret[i] || 1)}

  puts o*" "
else
  puts "NO"
end

def candidates(a, b)
  return nil if b%a != 0
  ret = []
  i = a
  while true
    if b%i == 0
      ret << i
    end
    i += a
    break if i > b
  end

  ret.sort.uniq
end

def do_assign(rules, idx, v, assign)
  assign[idx] = v
  rules.each do |i,j,a,b|
    if i == idx
      return nil if a*b%v != 0
      o = a*b/v
      assign[j] ||= o
      return nil if assign[j] != o
    end

    if j == idx
      return nil if a*b%v != 0
      o = a*b/v
      assign[i] ||= o
      return nil if assign[i] != o
    end
  end

  return true
end

def do_it(rules, cd, i, assign={})
  return assign if i > cd.keys.max

  i += 1 until cd[i]

  cd[i].each do |a|
    assign2 = assign.dup
    ret = do_assign(rules, i, a, assign2)
    if ret
      ret2 = do_it(rules, cd, i+1, assign2)
      return ret2 if ret2
    end
  end

  return nil
end

def hoge(data)
  return {} if data.empty?

  gg = {}
  ll = {}

  data.each do |i,j,a,b|
    ll[i] ||= b
    ll[j] ||= b

    ll[i] = ll[i].gcd(b)
    ll[j] = ll[j].gcd(b)

    gg[i] ||= a
    gg[j] ||= a

    gg[i] = gg[i]*a/gg[i].gcd(a)
    gg[j] = gg[j]*a/gg[j].gcd(a)
  end

  cd = {}
  gg.keys.each do |i|
    cd[i] = candidates(gg[i], ll[i])
    return nil unless cd[i]
  end

  ret = do_it(data, cd, 0, {})
end

n, m = gets.split.map(&:to_i)
data = []
m.times do
  data << gets.split.map(&:to_i)
end

ret = hoge(data)
if ret
  puts "YES"
  o = []
  1.upto(n){|i| o << (ret[i] || 1)}

  puts o*" "
else
  puts "NO"
end

$cache = {}
def pairs(a, b)
  d = b/a
  unless $cache[d]
    r = []
    1.upto(d/2) do |k|
      if d%k == 0
        r << [k, d/k]
      end
    end

    $cache[d] = r
  end

  $cache[d].map{|x,y| [x*a, y*a]}
end

def hoge(data,o=[])
  return o if data.empty?

  i, j, a, b = data[0]

  return nil if b%a != 0

  pairs(a, b).each do |x, y|
    o2 = o.dup
    o2[i] ||= x
    o2[j] ||= y

    data.each do |vv|
      if vv[0] == i
        return nil if vv[3]%x != 0
        o2[vv[1]] ||= vv[3]/x
        return nil if o2[vv[1]] != vv[3]/x
      end
      if vv[1] == i
        return nil if vv[3]%x != 0
        o2[vv[0]] ||= vv[3]/x
        return nil if o2[vv[0]] != vv[3]/x
      end

      if vv[0] == j
        return nil if vv[3]%y != 0
        o2[vv[1]] ||= vv[3]/y
        return nil if o2[vv[1]] != vv[3]/y
      end
      if vv[1] == j
        return nil if vv[3]%y != 0
        o2[vv[0]] ||= vv[3]/y
        return nil if o2[vv[0]] != vv[3]/y
      end
    end

    if o2[i] == x && o2[j] == y
      ret = hoge(data[1..-1], o2)
      return ret if ret
    end
  end

  return nil
end

n, m = gets.split.map(&:to_i)
data = []
m.times do
  data << gets.split.map(&:to_i)
end

ret = hoge(data)
if ret
  puts "YES"
  1.upto(n){|i|ret[i] ||= 1}

  puts ret[1..-1]*" "
else
  puts "NO"
end

$cache = {}
def pairs(a, b)
  d = b/a
  unless $cache[d]
    r = []
    1.upto(d) do |k|
      if d%k == 0
        r << [k, d/k]
      end
    end

    $cache[d] = r
  end

  $cache[d].map{|x,y| [x*a, y*a]}
end

def hoge(data,o=[])
  return o if data.empty?

  i, j, a, b = data[0]

  return nil if b%a != 0

  pairs(a, b).each do |x, y|
    o2 = o.dup
    o2[i] ||= x
    o2[j] ||= y

    data.each do |vv|
      vi, vj, va, vb = vv

      if vi == i
        return nil if vb%x != 0
        o2[vj] ||= vb*va/x
        return nil if o2[vj] != vb*va/x
      end

      if vj == i
        return nil if vb%x != 0
        o2[vi] ||= vb*va/x
        return nil if o2[vi] != vb*va/x
      end

      if vi == j
        return nil if vb%y != 0
        o2[vj] ||= vb*va/y
        return nil if o2[vj] != vb*va/y
      end

      if vj == j
        return nil if vb%y != 0
        o2[vi] ||= vb*va/y
        return nil if o2[vi] != vb*va/y
      end
    end

    if o2[i] == x && o2[j] == y
      ret = hoge(data[1..-1], o2)
      return ret if ret
    end
  end

  return nil
end

n, m = gets.split.map(&:to_i)
data = []
m.times do
  data << gets.split.map(&:to_i)
end

ret = hoge(data)
if ret
  puts "YES"
  1.upto(n){|i|ret[i] ||= 1}

  puts ret[1..-1]*" "
else
  puts "NO"
end


You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps:  select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$);  if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following:  select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0;  select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00;  select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum number of operations you can perform.

NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.

T = gets.to_i

T.times do
  n = gets.to_i
  s = gets.chomp
  stack = []
  cur = ''
  len = 0

  s.chars.reverse_each do |ch|
    if cur == ''
      cur = ch
      len = 1
    else
      if cur == ch
        len += 1
      else
        stack << len

        cur = ch
        len = 1
      end
    end
  end

  stack << len if len > 0
  ans = 0
  idx = -1

  until stack.empty?
    while stack[idx] && stack[idx] == 1
      idx -= 1
    end

    if stack[idx].nil?
      ans += (stack.size + 1) / 2
      break
    else
      stack[idx] -= 1
    end

    ans += 1
    stack.pop
    idx += 1 if idx < -1
  end

  puts ans
end


The BFS algorithm is defined as follows.  Consider an undirected graph with vertices numbered from $$$1$$$ to $$$n$$$. Initialize $$$q$$$ as a new queue containing only vertex $$$1$$$, mark the vertex $$$1$$$ as used.  Extract a vertex $$$v$$$ from the head of the queue $$$q$$$.  Print the index of vertex $$$v$$$.  Iterate in arbitrary order through all such vertices $$$u$$$ that $$$u$$$ is a neighbor of $$$v$$$ and is not marked yet as used. Mark the vertex $$$u$$$ as used and insert it into the tail of the queue $$$q$$$.  If the queue is not empty, continue from step 2.  Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $$$1$$$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) which denotes the number of nodes in the tree.  The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the sequence to check.

Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings:   $$$1, 2, 3, 4$$$,  $$$1, 3, 2, 4$$$. The ordering $$$1, 2, 4, 3$$$ doesn't correspond to any valid BFS order.

def f
  n = gets.to_i

  ri = Hash.new {|k,v| k[v]=[]}

  (1...n).each do
    a = gets.split.map(&:to_i)
    ri[a[0]] << a[1]
    ri[a[1]] << a[0]
  end

  cmp = gets.split.map(&:to_i)

  a  = Array.new(10,0)
  id = Array.new(10,0)

  (1..n).each do |i|
    a[i] = cmp[i-1]
    id[cmp[i-1]] = i
  end
  # ri = ri.sort.to_h
  # p ri
  # p a
  # p id
  q = [1]
  l = 0
  # p a
  while q.length > 0
    # p q
    x = q[0]
    q.shift
    # p q

    l += 1
    # print " al x #{a[l]} #{x}\n"
    if (x != a[l])
      return "No"
    end

    # pp ri
    ri[x].sort! { |a,b| id[a] <=> id[b] }
    # pp ri

    ri[x].each do |y|
      # print "#{id[y]} #{id[x]}\n"
      q << y if id[y] > id[x]
    end
  end
  return "Yes"
end

print f

def f
  n = gets.to_i

  ri = Hash.new {|k,v| k[v]=[]}

  (1...n).each do
    a = gets.split.map(&:to_i)
    ri[a[0]] << a[1]
    ri[a[1]] << a[0]
  end

  cmp = gets.split.map(&:to_i)

  a  = Array.new(10,0)
  id = Array.new(10,0)

  (1..n).each do |i|
    a[i] = i
    id[cmp[i-1]] = i
  end

  # p id
  # p a
  q = [1]
  l = 0
  # p a
  while q.length > 0
    # p q
    x = q[0]
    q.shift
    # p q

    l += 1
    # print " al x #{a[l]} #{x}\n"
    if (x != a[l])
      return "No"
    end

    # ri[x].sort! { |a,b| id[a] <=> id[b] }
    # p ri[x]

    ri[x].each do |y|
      # print "#{id[y]} #{id[x]}\n"
      if id[y] > id[x]
        q.push(id[y])
      end
    end
  end
  return "Yes"
end

print f

def f
  n = gets.to_i

  h = Hash.new {|k,v| k[v]=[]}

  (n-1).times do
    a = gets.split.map(&:to_i)
    h[a[0]] << a[1]
    h[a[1]] << a[0]
  end

  cmp = gets.split.map(&:to_i)

  id = Array.new(10,0)

  (1..n).each do |i|
    id[cmp[i-1]] = i
  end

  q = []
  q << 1
  l = 0

  while q.length > 0
    x = q[0]
    q.pop

    return "No" if (x != cmp[l])
    l += 1

    h[x].sort! { |a,b| id[a] <=> id[b] }

    p h[x]

    h[x].each do |y|
      q << y if id[y] > id[x]
    end
  end
  return "Yes"
end

print f

N = gets.to_i

h = Hash.new {|k,v| k[v]=Array.new}

(N-1).times do
  a = gets.split
  h[a[0]].push(a[1])
  h[a[1]].push(a[0])
end

cmp = gets.split

index = 1

cmp.each do |i|
  while h[i].include? cmp[index]
    index += 1
  end
  break if !h[i].include? cmp[index]
end

print index == cmp.length ? "Yes" : "No"

def f
  n = gets.to_i

  ri = Hash.new {|k,v| k[v]=[]}

  (1...n).each do
    a = gets.split.map(&:to_i)
    ri[a[0]] << a[1]
    ri[a[1]] << a[0]
  end

  cmp = gets.split.map(&:to_i)

  a  = Array.new(10,0)
  id = Array.new(10,0)

  (1..n).each do |i|
    a[i] = i
    id[cmp[i-1]] = i
  end

  q = [1]
  l = 0

  while q.length > 0
    x = q[0]
    q.shift

    l += 1

    if (x != a[l])
      return "No"
    end

    ri[x].sort! { |a,b| id[a] <=> id[b] }

    ri[x].each do |y|
      if id[y] > id[x]
        q << y
      end
    end
  end
  return "Yes"
end

print f

class Graph
  attr_accessor :graph

  def initialize(size)
    @graph = Hash.new { |h, k| h[k] = Array.new }
  end

  def <<(x)
    @graph[x[0]] << x[1]
  end

  def bfs(v)
    chain = []
    visited = Array.new(@graph.length, false)
    visited[v] = true

    queue = Queue.new
    queue.enq(v)

    while queue.length > 0
      v = queue.deq
      chain << v

      @graph[v].each do |i|
        if !visited[i]
          queue.enq(i)
          visited[i] = true
        end
      end
    end
    chain.join
  end
end

n = gets.to_i

g = Graph.new(n)

(n-1).times do
  v, w = gets.split.map(&:to_i)
  g << [v,w]
end

cmp = gets.split.join

found = 0

n.times do |i|
  if cmp == g.bfs(i)
    found = 1
    break
  end
end

print found == 1 ? "Yes" : "No"

N = gets.to_i

h = Hash.new {|k,v| k[v]=Array.new}

(N-1).times do
  a = gets.split
  h[a[0]] << a[1]
end

cmp = gets.split

queue = h[cmp[0]]

index = 1

cmp.each do |i|
  if queue.include? cmp[index]
    queue.delete(cmp[index])
    queue += h[cmp[index]]
    index += 1
  end
end

print index == cmp.length ? "Yes" : "No"

N = gets.to_i

h = Hash.new {|k,v| k[v]=Array.new}

(N-1).times do
  a = gets.split
  h[a[0]] << a[1]
end

cmp = gets.split

index = 1

cmp.each do |i|
  while h[i].include? cmp[index]
    index += 1
  end
end

print index == cmp.length ? "Yes" : "No"


You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of testcases. Each testcase consists of one line containing a single integer, $$$x$$$ $$$(2 \le x \le 10^9)$$$.

For each testcase, output a pair of positive integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9)$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$. It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

NoteIn the first testcase of the sample, $$$GCD(1,1)+LCM(1,1)=1+1=2$$$.In the second testcase of the sample, $$$GCD(6,4)+LCM(6,4)=2+12=14$$$.

gets.to_i.times do
	x = gets.to_i
	puts [1, x-1].join(' ')
end

t = gets.to_i
t.times do
  x = gets.to_i
  puts [1, x-1].join(" ")
end

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

=begin
a = p q
b = q r

gcd = q
lcm = pqr
q(1+pr)

若偶数，直接输出 a=b=x/2
若奇数 > 1，必然有 1+pr > 1
若奇数 = 1，无解（题目保证>=2）

简化：令q === 1，则1+pr总是>1
=end

def solve
	n = gets.to_i
	#q = 1
	#p = 1
	#r = n-1 # ((n/q)-1 ) / p
	puts "#{1} #{n-1}"
end

gets.to_i.times{ solve }

require 'set'; require 'prime'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i

t.times do
  x = gets.chomp.to_i
  puts "#{x-1} #{1}"
end

T = gets.to_i

T.times do
  x = gets.to_i

  if x > 2 && x % 2 == 0
    puts "2 #{x - 2}"
  else
    puts "1 #{x - 1}"
  end
end

# cook your code here

n = gets.to_i;

(0..n-1).each do |i|
    x = gets.to_i;
    p 1, x-1;
end

1.upto(gets.to_i) do
  puts "1 #{gets.to_i - 1}"
end

t = gets.chomp.to_i
(0...t).each do |_|
  x = gets.chomp.to_i
  print 1, ' ', x-1
  puts
end

# cook your code here

n = gets.to_i;

(0..n).each do |i|
    x = gets.to_i;
    p 1, x-1;
end

# cook your code here
x = gets.to_i;
p 1, x-1;


Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n and the number of a hill is equal to the distance in meters between it and the island. The distance between the n-th hill and the shore is also 1 meter.Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is d, the frog will jump from the island on the hill d, then — on the hill 2d, then 3d and so on until they get to the shore (i.e. find itself beyond the hill n).However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.

The first line contains three integers n, m and k (1 ≤ n ≤ 109, 1 ≤ m, k ≤ 100) — the number of hills, frogs and mosquitoes respectively. The second line contains m integers di (1 ≤ di ≤ 109) — the lengths of the frogs’ jumps. The third line contains k integers — the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.

In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line — their numbers in increasing order separated by spaces. The frogs are numbered from 1 to m in the order of the jump length given in the input data.

n,m,k = gets.chomp.split(/ /).map!{|x|x.to_i}
ma = gets.chomp.split(/ /).map!{|x|x.to_i}
ka = gets.chomp.split(/ /).map!{|x|x.to_i}
summin = k+1
mas = Array.new
for i in 0..m-1
	sum = 0
	for j in 0..k-1
		sum += 1 if ka[j] % ma[i] == 0
	end
	if summin > sum
		mas.clear
		mas.push(i+1)
		summin = sum
	elsif summin == sum
		mas.push(i+1)
	end
end
puts mas.length
puts mas.join(' ')

gets
a, b = 2.times.map{gets.split.map(&:to_i)}
c = a.each_with_index.map{|j, i| [b.count{|k| k % j == 0}, i + 1]}
c.reject!{|j, i| j != c.min[0]}
p c.size
puts c.map(&:last) * ' '

gets
a, b = 2.times.map{gets.split.map(&:to_i).sort}
c = a.each_with_index.map{|j, i| [b.count{|k| k % j == 0}, i + 1]}
c.reject!{|j, i| j != c.min[0]}
p c.size
puts c.map(&:last) * ' '


There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.

The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout. The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout. The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.

layout1 = gets.chomp
layout2 = gets.chomp
s = gets.chomp

res = ''
s.split("").each do |c|
    i = layout1.index(c.downcase)
    unless i
        res += c
    else
        if c == c.upcase
            res += layout2[i].upcase
        else
            res += layout2[i]
        end
    end
end
puts res

a,b,c=$<.map &:chomp
puts c.tr(a+a.upcase,b+b.upcase)

#!/usr/bin/ruby -w

class String

  def is_upper?
    not self.match /[[:lower:]]/
  end

  def is_lower?
    not self.match /[[:upper:]]/
  end

end

str1 = gets
str2 = gets
strr = gets

str_siz = strr.size
str_siz.times do |i|
  idx = str1.index(strr[i].downcase)
  if idx != nil then
    if strr[i].is_upper? then
      strr[i] = str2[idx].capitalize
    else
      strr[i] = str2[idx]
    end
  end
end
puts strr

fs = gets.chomp
ss = gets.chomp
fsl = fs.upcase
ssl = ss.upcase

ans = ''
gets.chomp.chars.each do |s|
  if id = fs.index(s)
    ans += ss[id]
  elsif id = fsl.index(s)
    ans += ssl[id]
  else
    ans += s
  end
end

puts ans

f = gets.strip.split("")
s = gets.strip.split("")
t = gets.strip
ans = ""
t.each_char do |c|
    id = f.index c.downcase
    if /[[:upper:]]/.match c
        ans += s[id].upcase
    elsif /[[:digit:]]/.match c
        ans += c
    else
        ans += s[id]
    end
end
puts ans

str1=gets.chomp
str2=gets.chomp

hs={}
str1.size.times{|i|
	e1=str1[i]
	e2=str2[i]
	hs[e1]=e2
	hs[e1.upcase]=e2.upcase
}
str3=gets.chomp
str3.chars.each{|e|
	if hs.member?(e)==false
		print e
	else
		print hs[e]
	end
}
print "\n"

a = gets
b = gets
h = {}
(0...26).each { |i| h[a[i]] = b[i] }
puts gets.chomp('').split('').map { |x|
  c = h[x.downcase] || x
  x =~ /[A-Z]/ ? c.upcase : c
}.join

a = gets.chomp!
b = gets.chomp!
t = gets.chomp!

h = Hash.new
26.times do |i|
	h[a[i]] = b[i]
end

f = ""
t.chars do |c|
	if c == c.downcase
		f.insert(-1, h[c] || c)
	else
		f.insert(-1, h[c.downcase].upcase)
	end
end

puts f

first=gets.chomp
second=gets.chomp
third=gets.chomp

third.each_char do |x|
if x=~/[[:digit:]]/
    print x
    next
end
index = first.index(x.downcase)

if x == x.upcase
    print second[index].upcase
else
    print second[index]
    end
end

k1 = gets.chomp
k2 = gets.chomp

map = {}
for i in 0 ... 26
  map[k1[i]] = k2[i]
end

s = gets.chomp
t = s.split('').map{|c|
  if c != c.downcase
    map[c.downcase].upcase
  else
    map[c] ? map[c] : c
  end
}.join()
puts t

a,b,c=$<.map &:chomp
puts c.tr(b+b.upcase,a+a.upcase)

#!/usr/bin/ruby -w

class String

  def is_upper?
    not self.match /[[:lower:]]/
  end

  def is_lower?
    not self.match /[[:upper:]]/
  end

end

puts 'Hello World'

str1 = gets
str2 = gets
strr = gets

str_siz = strr.size
str_siz.times do |i|
  idx = str1.index(strr[i].downcase)
  if idx != nil then
    if strr[i].is_upper? then
      strr[i] = str2[idx].capitalize
    else
      strr[i] = str2[idx]
    end
  end
end
puts strr


IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from $$$1$$$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first and the only line contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$), describing the initial string formed by magnets. The string $$$s$$$ consists only of characters 'a' and 'b'.

Output exactly $$$|s|$$$ integers. If IA should reverse the $$$i$$$-th prefix (that is, the substring from $$$1$$$ to $$$i$$$), the $$$i$$$-th integer should be equal to $$$1$$$, and it should be equal to $$$0$$$ otherwise. If there are multiple possible sequences leading to the optimal answer, print any of them.

NoteIn the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.In the second example, she can reverse any subset of prefixes — all letters are 'a'.

str = gets.strip
n = str.size
seq = Array.new(n,0)

1.upto(n-1).each do |p|
  if str[p]=='a'
    if seq[p-1]==0
      seq[p-1]=1
    else
      seq[p-1]=0
    end
    seq[p]=1
  end
end

puts seq.join(" ")


Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.  There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and i + 1 are adjacent for every i, 1 ≤ i < n. In addition, sectors 1 and n are also adjacent.Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.Unstable cells are marked red in the figure. Stable cells are marked green.Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.

The first line contains integer n (3 ≤ n ≤ 1000) — the number of main threads. The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1 ≤ ki ≤ 105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1 ≤ pij ≤ 105; 1 ≤ j ≤ ki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web. It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.

Print a single integer — the number of unstable cells in Paw the Spider's web.

s,m,n=0,1e6,Array.new(n=gets.to_i){gets.split.map(&:to_i)[1..-1].sort}
(n+n[0,2]).each_cons(3){|a,b,c|r,b,*e=b.dup
b&&(a,*w=a.drop_while{|i|i<r};a||=m
c,*r=c.drop_while{|i|i<r};c||=m
g=h=0
loop{b>a||b>c ? (a>b ? (h+=1;c=r.shift||m):(g+=1;a=w.shift||m)):(g!=h&&s+=1
b>m||(g=h;break if !b=e.shift))})}
p s

#require "profile"

time = Time.now

STDOUT.sync = true

net = Array.new(n = gets.to_i) do
    gets " "
    gets.split.map(&:to_i).sort
end

net += net.take(2)

s = 0

net.each_cons(3) do |l1t,l2t,l3t| #puts [l2t].inspect
    l2 = l2t.dup; start = l2.shift; #puts start
    l1 = l1t.dup; l1 = l1.drop_while{ |i| i < start }
    l3 = l3t.dup; l3 = l3.drop_while{ |i| i < start }
    a = l1.shift || 1000000
    next unless b = l2.shift
    c = l3.shift || 1000000
    g1 = g2 = 0
    loop do
        #puts [a,b,c,g1,g2,s].inspect
        if b <= a && b <= c
            if b == 1000000
                s += 1 if g1 != g2
                break
            end
            #puts "b"
            s += 1 if g1 != g2
            g1 = g2 = 0
            break unless b = l2.shift
        elsif a <= b && a <= c
            #puts "a"
            g1 += 1
            a = l1.shift || 1000000
        else
            #puts "c"
            g2 += 1
            c = l3.shift || 1000000
        end
    end
    #puts s
end

puts s

#puts Time.now - time

n = (1..(n=gets.to_i)).map do
    gets.split.map(&:to_i).drop(1).sort
end

s = 0
m = 1e6

(n + n[0,2]).each_cons(3) do |a,b,c|
    r,b,*e = b.dup
    next if !b
    a,*w = a.dup.drop_while{ |i| i < r }; a ||= m
    c,*r = c.dup.drop_while{ |i| i < r }; c ||= m
    g = h = 0
    loop do
        b <= a && b <= c ? (
            s += 1 if g != h
            (b <= m) && ( g = h; break if !b = e.shift )
        ) : a <= b && a <= c ?
        ( g += 1; a = w.shift || m ) :
        ( h += 1; c = r.shift || m )
    end
end

puts s

#require "profile"

time = Time.now

STDOUT.sync = true

net = Array.new(n = gets.to_i) do
    gets " "
    gets.split.map(&:to_i).sort
end

net += net.take(2)

s = 0

net.each_cons(3) do |l1t,l2t,l3t| #puts [l2t].inspect
    l2 = l2t.dup; start = l2.shift; #puts start
    l1 = l1t.dup; l1 = l1.drop_while{ |i| i < start }
    l3 = l3t.dup; l3 = l3.drop_while{ |i| i < start }
    a = l1.shift || 1000000
    next unless b = l2.shift
    c = l3.shift || 1000000
    g1 = g2 = 0
    loop do
        #puts [a,b,c,g1,g2,s].inspect
        if b <= a && b <= c
            if b == 1000000
                s += 1 if g1 != g2
                break
            end
            #puts "b"
            s += 1 if g1 != g2
            g1 = g2 = 0
            break unless b = l2.shift
        elsif a <= b && a <= c
            #puts "a"
            g1 += 1
            a = l1.shift || 1000000
        else
            #puts "c"
            g2 += 1
            c = l3.shift || 1000000
        end
    end
    #puts s
end

puts s

puts Time.now - time


Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days — the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.

The first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1 ≤ ci ≤ k) — current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1 ≤ li, ri ≤ n, li ≠ ri) — indices of socks which Arseniy should wear during the i-th day.

Print one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.

NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors.

def solve
  n, m, k = gets.split.map(&:to_i)
  cs = gets.split.map(&:to_i)
  uf = UnionFind.new(n)
  m.times do
    l, r = gets.split.map(&:to_i)
    uf.unit(l - 1, r - 1)
  end
  g2c = {}
  cs.each_with_index do |e, i|
    x = uf.find(i)
    colors = (g2c[x] ||= {})
    colors[e] ||= 0
    colors[e] += 1
  end
  ans = 0
  g2c.each_value do |colors|
    vs = colors.values
    sum = vs.inject(0, &:+)
    max = vs.max
    ans += sum - max
  end
  puts ans
end

class UnionFind
  def initialize(size)
    @parent = (0...size).to_a
    @rank = Array.new(size, 0)
  end

  def find(x)
    return x if @parent[x] == x
    return (@parent[x] = find(@parent[x]))
  end

  def unit(x, y)
    x, y = find(x), find(y)
    return if x == y
    if @rank[x] < @rank[y]
      @parent[x] = y
    else
      @parent[y] = x
      @rank[x] += 1 if @rank[x] == @rank[y]
    end
  end

  def same(x, y)
    find(x) == find(y)
  end
end

solve

# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

class SNM
    def initialize(n)
        @a = (0..n).to_a
    end

    def get(v)
        while @a[v] != v
            @a[v] = @a[@a[v]]
            v = @a[v]
        end
        return v
    end

    def join(u, v)
        pu = get(u)
        pv = get(v)
        return if pu == pv
        if rand < 0.5
            @a[pu] = @a[pv]
        else
            @a[pv] = @a[pu]
        end
    end
end

n, m, k = read_vector_int
colors = [nil] + read_vector_int

snm = SNM.new(n)
m.times.each do
    v, u = read_vector_int
    snm.join(v, u)
end

colors_in_comp = Array.new(n + 1) { [] }
(1..n).each do |id|
    comp_id = snm.get(id)
    colors_in_comp[comp_id].push(colors[id])
end

ans = 0
colors_in_comp.each do |c|
    next if c.empty?

    cnt = Hash.new(0)
    c.sort!
    c.each{ |col| cnt[col] += 1 }
    max_cnt = cnt.values.max
    ans += c.size - max_cnt
end

puts ans

n, m, k = gets.split.map(&:to_i)
$socks = [nil] + gets.split.map(&:to_i)
days = m.times.map{gets.split.map(&:to_i)}

$visited = Array.new(n + 1)
$e = Array.new(n + 1){Array.new}

days.each do |l, r|
  $e[l] << r
  $e[r] << l
end

def bfs(u)
  todo = []
  push = lambda do |v|
    $visited[v] = true
    todo << v
  end
  push.(u)
  while u = todo.shift
    $rainbow[$socks[u]] += 1
    $e[u].each do |v|
      next if $visited[v]
      push.(v)
    end
  end
end

ans = 0
1.upto(n) do |i|
  next if $visited[i]
  $rainbow = Hash.new(0)
  bfs(i)
  v = $rainbow.values
  ans += v.inject(:+) - v.max
end

puts ans


Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m > 2n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat.  The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.

The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.

Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.

n,m=gets.split.map(&:to_i)
a=[*1..(m+3)/4*4].each_slice(2).each_slice(n).to_a
puts a.shift.zip(*a).flat_map{|(a,b),(c,d)|[c,a,d,b]}.select{|e|e&&e<=m}*' '

n, m = readline.split(' ').collect(&:to_i)
arr = []
1.upto(n) do |i|
  arr += [i * 2 - 1 + n * 2, i * 2 - 1, i * 2 + n * 2, i * 2]
end
arr.keep_if {|num| num <= m}
arr.each_with_index do |num, ind|
  if ind != 0
    print " "
  end
  print num
end
puts ""

a=gets.chomp.split(" ")
n=a[0].to_i
m=a[1].to_i
i=1
p=2
n.times do
    if (i+2*n)<=m
        print "#{i+2*n} "
    end
    if i<=m
        print "#{i} "
    end

    i+=2
     if (p+2*n)<=m
        print "#{p+2*n} "
    end
     if p<=m
        print "#{p} "
    end

    p+=2
end

#!/usr/bin/ruby
n,m=gets.split.map(&:to_i)
m0=(m+3)/4
puts [*1..m0*4].each_slice(2).each_slice(m0).to_a.transpose.flat_map{|(a,b),(c,d)|[c,a,d,b]}.select{|e|e<=m}*' '


Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $$$26$$$ lowercase Latin letters will be arranged in some order.Polycarp uses the same password $$$s$$$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $$$s$$$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $$$s$$$, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Then $$$T$$$ lines follow, each containing one string $$$s$$$ ($$$1 \le |s| \le 200$$$) representing the test case. $$$s$$$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $$$s$$$.

For each test case, do the following:   if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of $$$26$$$ lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them.

5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza

YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

T = gets.to_i

T.times do
  s = gets.chomp

  if s.size == 1
    puts 'YES'
    puts [*'a'..'z'].join
    next
  end

  edge = Hash.new { |h, k| h[k] = [] }

  s.chars.each_cons(2) do |v, u|
    edge[v] |= [u]
    edge[u] |= [v]
  end

  use_key = edge.keys
  vc = use_key.size
  remain = [*'a'..'z'] - use_key
  min_d = Float::INFINITY
  max_d = 0
  one_cnt = 0

  edge.each do |k, list|
    len = list.size

    one_cnt += 1 if len == 1

    min_d = len if min_d > len
    max_d = len if max_d < len
  end

  if max_d >= 3
    puts 'NO'
    next
  end

  if one_cnt != 2
    puts 'NO'
    next
  end

  root = edge.find { |_, list| list.size == 1 }
  queue = [root[0]]
  board = []
  visited = Hash.new(false)

  until queue.empty?
    key = queue.shift

    next if visited[key]
    visited[key] = true

    board << key

    edge[key].each do |u|
      queue << u
    end
  end

  res = board + remain

  if res.size < 26
    puts 'NO'
  else
    puts 'YES'
    puts res.join
  end
end


Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?

The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

def dfs(u, g, used)
  used[u], result = true, 0
  g[u].each do |v, cost|
    result += cost + dfs(v, g, used) unless used[v]
  end
  result
end

def solve(n, g)
  left, right = g[0]

  g[0] = [left]
  alpha = dfs(0, g, Array.new(n, false)) + g[right.first].assoc(0)[-1]

  g[0] = [right]
  beta = dfs(0, g, Array.new(n, false)) + g[left.first].assoc(0)[-1]

  [alpha, beta].min
end

n = gets.to_i
g = Array.new(n) { [] }

n.times do
  a, b, c = gets.split.map { |v| v.to_i }
  a -= 1
  b -= 1
  g[a] << [b, 0]
  g[b] << [a, c]
end

puts solve(n, g)

def dfs(u, g, used)
  used[u] = true
  result = 0
  g[u].each do |v, cost|
    result += cost + dfs(v, g, used) unless used[v]
  end
  result
end

def solve(n, g)
  left, right = g[0]

  g[0] = [left]
  alpha = dfs(0, g, Array.new(n, false)) + g[right.first].assoc(0)[-1]

  g[0] = [right]
  beta = dfs(0, g, Array.new(n, false)) + g[left.first].assoc(0)[-1]

  [alpha, beta].min
end

n = gets.to_i
g = Array.new(n) { [] }

n.times do
  a, b, c = gets.split.map { |v| v.to_i }
  a -= 1
  b -= 1
  g[a] << [b, 0]
  g[b] << [a, c]
end

puts solve(n, g)

def dfs(u, g, used)
  used[u] = true
  result = 0
  g[u].each do |pair|
    v, cost = pair
    result += cost + dfs(v, g, used) if not used[v]
  end
  result
end

def solve(n, g)
  first, last = g[0]

  g[0] = [first]
  alpha = dfs(0, g, Array.new(n, false)) + g[last.first].assoc(0)[-1]

  g[0] = [last]
  beta = dfs(0, g, Array.new(n, false)) + g[first.first].assoc(0)[-1]

  [alpha, beta].min
end

n = gets.to_i
g = Array.new(n) { [] }

n.times do
  a, b, c = gets.split.map { |v| v.to_i }
  a -= 1
  b -= 1
  g[a] << [b, 0]
  g[b] << [a, c]
end

puts solve(n, g)

def gao(e, v, p)
	e[v].map{|w, c| w == p ? 0 : c + gao(e, w, v)}.inject(&:+)
end

n = gets.to_i
e = Array.new(n + 1){[]}
y = 0
(n - 1).times do
	a, b, c = gets.split.map(&:to_i)
	e[a] << [b, 0]
	e[b] << [a, c]
	y += c
end
a, b, c = gets.split.map(&:to_i)
x = gao(e, a, -1)
p [x + c, y - x].min

n=gets.to_i
g=Array.new(n){[]}
n.times{
    input=gets.split.map(&:to_i)
    a=input[0]-1
    b=input[1]-1
    c=input[2]
    g[a].push([a,b,c])
    g[b].push([a,b,c])
}
res=[]
for q in 0..1
    cost=0
    v=g[0][q][1]
    if v==0 then
        cost+=g[0][q][2]
        v=g[0][q][0]
    end
    back=g[0][q]
    loop do
        if v==0 then
            break
        end
        for i in 0..1
            if g[v][i]!=back then
                back=g[v][i]
                if g[v][i][1]==v then
                    cost+=g[v][i][2]
                    v=g[v][i][0]
                else
                    v=g[v][i][1]
                end
                break
            end
        end
    end
    res.push(cost)
end
puts res.min

h=Array.new(gets.to_i){[]}
while gets
a,b,c=$_.split.map &:to_i
h[a-1]<<[b-1,0]
h[b-1]<<[a-1,c]
end
p h[0].map{|a,s|x=0
while a>0
h[a].map{|b,c|if b!=x
a,x=b,a
s+=c
break
end}
end
s}.min

#!/usr/bin/ruby

N = gets.to_i

cities = Array.new(N + 1) {Array.new}

N.times do
  (a, b, c) = gets.split.map{|e| e.to_i}

  cities[a].push [b, 0]
  cities[b].push [a, c]
end

prev = 1
now = cities[1][0][0]
cost0 = cities[1][0][1]

(N - 1).times do # not N - 2
  id = (cities[now][0][0] == prev) ? 1 : 0
  prev = now
  cost0 += cities[now][id][1]
  now = cities[now][id][0]
end

prev = 1
now = cities[1][1][0]
cost1 = cities[1][1][1]

(N - 1).times do # not N - 2
  id = (cities[now][0][0] == prev) ? 1 : 0
  prev = now
  cost1 += cities[now][id][1]
  now = cities[now][id][0]
end

puts [cost0, cost1].min

p = Array.new(101)
101.times{|i|
  p[i]=Array.new(101,0)
}

def find_cost(prev, now, n, p)
  res, d = 0, p[prev][now]
  #puts "find_cost: "+prev.to_s+" "+now.to_s
  res = res - d if (d<0)
  return res if (now==1)
  (1..n).each{|i|
    res += find_cost(now, i, n, p) if (p[now][i].to_i!=0)&&(i!=prev)
  }
  res
end

n = gets.chomp.to_i

n.times { |i|
  a,b,c = gets.chomp.split(' ').map{|it| it.to_i}
  p[a][b], p[b][a] = c, -c
}

ans = -1

(2..n).each{|i|
  if p[1][i]!=0
    candidate = find_cost(1, i, n, p)
    ans = candidate if (ans==-1  ||  candidate < ans)
  end
}

puts ans

h=Array.new(gets.to_i){[]}
while gets
  a,b,c=$_.split.map &:to_i
  h[a-1]<<[b-1,0]
  h[b-1]<<[a-1,c]
end
p h[0].map{|a,s|x=0
  while a>0
    h[a].map{|b,c|
      if b!=x
        a,x=b,a
        s+=c
        break
      end
    }
  end
  s
}.min

require "pp"

class Edge
  def initialize (src,dst,cost)
    @src = src
    @dst = dst
    @cost = cost
  end

  attr_accessor :src, :dst, :cost
end

edges = Array.new
num = gets.to_i
cost = 0

for i in 0..num-1
	ary = gets.split.map{|elem| elem.to_i}
	edges << Edge.new(ary[0],ary[1],ary[2])
	cost += ary[2]
end

first = edges.shift
arc = Edge.new(first.src,first.dst,0)

while edges.length > 0
	edges.each_with_index do |edge, i|
		if edge.src == arc.dst
			arc.dst = edge.dst
			edges.delete_at(i)
		elsif edge.dst == arc.dst
			arc.dst = edge.src
			arc.cost += edge.cost
			edges.delete_at(i)
		end
	end
end

p [arc.cost,cost - arc.cost].min

# start 2010/7/28 17:11
# implementation finish at 18:57

#ring_road

class Edge
  def initialize(u,v,inv_cost)
    @src = u
    @dst = v
    @inv_cost = inv_cost
  end

  attr_accessor :src, :dst, :inv_cost
end

#f = open("hoge.txt")

num = gets.to_i
#num = f.gets.to_i
#p num

edges = Array.new
edge_subsets = Array.new

total_cost = 0

for i in 0..num-1
	#ary = f.gets.split.map {|elem| elem.to_i}
	ary = gets.split.map {|elem| elem.to_i}
	# p ary

	# e(u,v)  ,  inv_cost_of_e �Ƃ���format.
	edges << Edge.new(ary[0],ary[1],ary[2])

	total_cost += ary[2]
end

#circle�����
	#edge��subset������čs���Amerge���Ă���

edges.each {|edge|
	if edge_subsets.length == 0
		subset = Array.new
		subset << edge.src << edge.dst
		edge_subsets << subset
	else
		merge_flg = false

		edge_subsets.each{|subset|
			merge_flg = true

			if edge.src == subset.first
				subset.unshift edge.dst
			elsif edge.src == subset.last
				subset << edge.dst
			elsif edge.dst == subset.first
				subset.unshift edge.src
			elsif edge.dst == subset.last
				subset << edge.src
			else
				merge_flg = false
			end

			if merge_flg
				break
			end
		}

		unless merge_flg
			subset = Array.new
			subset << edge.src << edge.dst
			edge_subsets << subset
		end
	end
}

#p edge_subsets

#subset���m��merge

#puts "merge subsets"

while edge_subsets.length > 1
	temp_ss = edge_subsets.pop

	edge_subsets.each{|subset|
		if temp_ss.first == subset.first
			temp_ss.reverse!
			temp_ss.pop
			subset = temp_ss + subset
		elsif temp_ss.first == subset.last
			temp_ss.shift
			subset.concat temp_ss
		elsif temp_ss.last == subset.first
			temp_ss.pop
			subset = temp_ss + subset
		elsif temp_ss.last == subset.last
			temp_ss.reverse!
			temp_ss.shift
			subset.concat temp_ss
		end
	}
end

#p edge_subsets

circle = edge_subsets.pop
#p circle

rev_cost = 0

edges.each {|edge|
	idx = circle.index(edge.src)
	if circle[idx+1] != edge.dst
		#p edge
		rev_cost += edge.inv_cost
	end
}

alt = total_cost - rev_cost
if rev_cost < alt
	p rev_cost
else
	p alt
end

=begin

[4, 6, 1, 5, 3, 2]

---
n=6

1 5
5 3

2 4

1 6

2 3
4 6

=end

num_of_edge = gets
edge_list = []
while line = gets
	obj = {}
	obj[:start], obj[:dest], obj[:cost] = line.chomp.split.map{|s| s.to_i}
	edge_list << obj
end
cost_pair = [0,0]
ring_obj = edge_list.pop
cost_pair[0] += ring_obj[:cost]

while edge_list.length > 0
	del_obj = edge_list.find{|obj|
		if    obj[:start] == ring_obj[:dest]
			ring_obj[:dest] = obj[:dest]
			cost_pair[0] += obj[:cost]
		elsif obj[:dest] == ring_obj[:dest]
			cost_pair[1] += obj[:cost]
			ring_obj[:dest] = obj[:start]
		end
	}
	edge_list.delete(del_obj)
end
puts cost_pair.min

__END__
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42

num_of_edge = gets.to_i
edge_list = []
ring_hash = Hash.new
while line = gets
	obj = {}
	obj[:start], obj[:dest], obj[:cost] = line.chomp.split.map{|s| s.to_i}
	edge_list << obj
end

edge_list.each{|obj|
	if !ring_hash.include?(obj[:start])
		ring_hash[ obj[:start] ] = obj[:dest]
		obj[:clock_wise] = true
	else
		ring_hash[ obj[:dest] ]  = obj[:start]
	end
}
puts [ edge_list.select{|obj| obj[:clock_wise] }.inject(0){|sum, obj| sum += obj[:cost] } , edge_list.select{|obj| !obj[:clock_wise] }.inject(0){|sum, obj| sum += obj[:cost] } ].min

num_of_edge = gets.to_i
edge_list                = []
clock_wise_edge_list     = []
non_clock_wise_edge_list = []
ring_hash = Hash.new
while line = gets
	obj = {}
	obj[:start], obj[:dest], obj[:cost] = line.chomp.split.map{|s| s.to_i}
	edge_list << obj
end
edge_list.each{|obj|
	if !ring_hash.include?(obj[:start])
		ring_hash[ obj[:start] ] = obj[:dest]
		clock_wise_edge_list << obj
	else
		ring_hash[ obj[:dest] ]  = obj[:start]
		non_clock_wise_edge_list << obj
	end
}
puts [ clock_wise_edge_list.inject(0){|sum, obj| sum += obj[:cost] } , non_clock_wise_edge_list.select{|obj| !obj[:clock_wise?] }.inject(0){|sum, obj| sum += obj[:cost] } ].min

num_of_edge = gets.to_i
edge_list = []
ring_hash = Hash.new
while line = gets
	obj = {}
	obj[:start], obj[:dest], obj[:cost] = line.chomp.split.map{|s| s.to_i}
	edge_list << obj
end
edge_list.each{|obj|
	if ring_hash.value?(obj[:start])
		ring_hash[ obj[:start] ] = obj[:dest]
	elsif ring_hash.key?(obj[:start])
		ring_hash[ obj[:dest] ]  = obj[:start]
		obj[:reverse] = true
	else
		ring_hash[ obj[:start] ] = obj[:dest]
	end
}
puts [ edge_list.select{|obj| obj[:reverse] }.inject(0){|sum, obj| sum += obj[:cost] } , edge_list.select{|obj| !obj[:reverse] }.inject(0){|sum, obj| sum += obj[:cost] } ].min

gets
edge_list = []
ring_hash = Hash.new
while line = gets
	obj = {}
	obj[:start], obj[:dest], obj[:cost] = line.chomp.split.map{|s| s.to_i}
	edge_list << obj
end
edge_list.each{|obj|
	if !ring_hash.include?(obj[:start])
		ring_hash[ obj[:start] ] = obj[:dest]
		obj[:clock_wise?] = true
	else
		ring_hash[ obj[:dest] ]  = obj[:start]
	end
}
puts [ edge_list.select{|obj| obj[:clock_wise?] }.inject(0){|sum, obj| sum += obj[:cost] } , edge_list.select{|obj| !obj[:clock_wise?] }.inject(0){|sum, obj| sum += obj[:cost] } ].min


You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".

The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.

Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.

NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".

s = gets.chomp.split(/[,;]/, -1)
number = []
nonnumber = []
s.each do |w|
  if w.match(/^[0-9]+$/) then
    if w.length >= 2 and w[0] == "0" then
      nonnumber << w
    else
      number << w
    end
  else
    nonnumber << w
  end
end
if number.length == 0 then
  puts "-"
else
  p number.join(",")
end
if nonnumber.length == 0 then
  puts "-"
else
  p nonnumber.join(",")
end

str = gets
words = str.split(/,|;/)
words[words.length-1] = words[words.length-1][0...words[words.length-1].length-1]
nums = []
others = []
words.each do |word|
	if word.to_i.to_s == word
		nums.push(word)
	else
		others.push(word)
	end
end
if nums.empty?
	puts "-"
else
	puts "\"#{nums.join(',')}\""
end
if others.empty?
	puts "-"
else
	puts "\"#{others.join(',')}\""
end

str = gets
str = str[0...str.length-1]
words = str.split(/,|;/)
nums = []
others = []
words.each do |word|
	if word.to_i.to_s == word
		nums.push(word)
	else
		others.push(word)
	end
end
if nums.empty?
	puts "-"
else
	puts "\"#{nums.join(',')}\""
end
if others.empty?
	puts "-"
else
	puts "\"#{others.join(',')}\""
end


You are given a integer $$$n$$$ ($$$n > 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$:   $$$s > 0$$$,  $$$s$$$ consists of $$$n$$$ digits,  no digit in $$$s$$$ equals $$$0$$$,  $$$s$$$ is not divisible by any of it's digits.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case contains one positive integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, print an integer $$$s$$$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $$$s$$$, print any solution.

#!usr/bin/env ruby

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

n = gets.to_i

n.times do
  a = gets.to_i

  if a == 1
    puts '-1'
  else
    puts ('9' * (a - 1) + '8')
  end
end

T = gets.to_i

T.times do
  n = gets.to_i

  if n == 1
    puts -1
  else
    puts '2' + '3' * (n - 1)
  end
end

def main
  t = gets.chomp.to_i
  t.times { solve }
end

def solve
  n = gets.chomp.to_i
  # a, b, c = gets.chomp.split.map(&:to_i)
  # S = gets.chomp.chars
  # p n
  # p [a, b, c]
  if n == 1
    p(-1)
  else
    ans = "5" * (n-1)
    ans += "4"
    print (ans + "\n")
  end
end

main

t = gets.to_i
t.times do
  n = gets.to_i
  if n == 1
    puts -1
  else
    case n % 3
    when 0
      puts "2" * (n - 1) + "3"
    when 1
      puts "2" * (n - 2) + "33"
    when 2
      puts "2" * (n - 1) + "3"
    end
  end
end

1.upto(gets.to_i) do
  n = gets.to_i

  if n == 1
    puts -1
    next
  end

  if (2*(n-1) + 3).modulo(3).zero?
    puts '2' * (n-2) + '33'
  else
    puts '2' * (n-1) + '3'
  end
end

def main
  t = gets.chomp.to_i
  t.times { solve }
end

def solve
  n = gets.chomp.to_i
  # a, b, c = gets.chomp.split.map(&:to_i)
  # S = gets.chomp.chars
  # p n
  # p [a, b, c]
  if n == 1
    p(-1)
  else
    ans = "2" * (n-1)
    ans += "9"
    print (ans + "\n")
  end
end

main