Let $$$n$$$ be a positive integer. Let $$$a, b, c$$$ be nonnegative integers such that $$$a + b + c = n$$$.Alice and Bob are gonna play rock-paper-scissors $$$n$$$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $$$a$$$ times, paper $$$b$$$ times, and scissors $$$c$$$ times.Alice wins if she beats Bob in at least $$$\lceil \frac{n}{2} \rceil$$$ ($$$\frac{n}{2}$$$ rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors:  rock beats scissors;  paper beats rock;  scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers $$$a, b, c$$$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then, $$$t$$$ testcases follow, each consisting of three lines:    The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).  The second line contains three integers, $$$a, b, c$$$ ($$$0 \le a, b, c \le n$$$). It is guaranteed that $$$a + b + c = n$$$.  The third line contains a string $$$s$$$ of length $$$n$$$. $$$s$$$ is made up of only 'R', 'P', and 'S'. The $$$i$$$-th character is 'R' if for his $$$i$$$-th Bob plays rock, 'P' if paper, and 'S' if scissors.

For each testcase:    If Alice cannot win, print "NO" (without the quotes).  Otherwise, print "YES" (without the quotes). Also, print a string $$$t$$$ of length $$$n$$$ made up of only 'R', 'P', and 'S' — a sequence of hands that Alice can use to win. $$$t$$$ must contain exactly $$$a$$$ 'R's, $$$b$$$ 'P's, and $$$c$$$ 'S's.  If there are multiple answers, print any of them.  The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.

NoteIn the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and $$$3 \ge \lceil \frac{3}{2} \rceil = 2$$$, so Alice wins.In the second testcase, the only sequence of hands that Alice can play is "RRR". Alice beats Bob only in the last hand, so Alice can't win. $$$1 < \lceil \frac{3}{2} \rceil = 2$$$.

WIN = {
  'S' => 'P',
  'P' => 'R',
  'R' => 'S'
}

LOSE = {
  'P' => 'S',
  'R' => 'P',
  'S' => 'R'
}

def solve(n, a, b, c, seq)
  me = {'R' => a, 'P' => b, 'S' => c}
  other = seq.inject(Hash.new(0)) { |m, c| m[c] += 1; m }
  wins = me.inject(0) { |m, (k, v)| m += [v, other[WIN[k]]].min; m  }
  return "NO" if wins < (n / 2.0).ceil
  to_win = {}
  to_any = {}
  me.each do |k, v|
    to_win[k] = [v, other[WIN[k]]].min
    to_any[k] = v - [v, other[WIN[k]]].min
  end
  res = []
  seq.each do |c|
    # puts to_win
    # puts to_any
    if to_win[LOSE[c]] > 0
      to_win[LOSE[c]] -= 1
      res << LOSE[c]
    else
      play = to_any.select { |k, v|  !v.zero? }.keys.first
      # puts "play #{play}"
      to_any[play] -= 1
      res << play
    end
  end
  wins >= (n / 2.0).ceil ? "YES\n#{res.join('')}" : "NO"
  # res.size == seq.size ? "YES\n#{res.join('')}" : "NO"
end

gets.strip.to_i.times do
  n = gets.strip.to_i
  a, b, c = gets.strip.split(' ').map(&:to_i)
  seq = gets.strip.split('')
  puts solve(n, a, b, c, seq)
end

WIN = {
  'P' => 'S',
  'S' => 'R',
  'R' => 'P'
}

def solve(n, a, b, c, seq)
  me = {'R' => a, 'P' => b, 'S' => c}
  other = seq.inject(Hash.new(0)) { |m, c| m[c] += 1; m }
  res = []
  wins = 0
  seq.each_with_index do |c, i|
    if me[WIN[c]] > 0
      res << WIN[c]
      me[WIN[c]] -= 1
      other[c] -= 1
      wins += 1
    else
      left = me.select { |k, v| !v.zero? }.keys
      to_play = left.min do |non_win|
        other[WIN[non_win]]
      end
      res << to_play
      me[to_play] -= 1
      other[c] -= 1
    end
  end
  wins >= (n / 2.0).ceil ? "YES\n#{res.join('')}" : "NO"
  # res.size == seq.size ? "YES\n#{res.join('')}" : "NO"
end

gets.strip.to_i.times do
  n = gets.strip.to_i
  a, b, c = gets.strip.split(' ').map(&:to_i)
  seq = gets.strip.split('')
  puts solve(n, a, b, c, seq)
end

WIN = {
  'S' => 'P',
  'P' => 'R',
  'R' => 'S'
}

def solve(n, a, b, c, seq)
  me = {'R' => a, 'P' => b, 'S' => c}
  other = seq.inject(Hash.new(0)) { |m, c| m[c] += 1; m }
  res = []
  wins = 0
  seq.each_with_index do |c, i|
    if me[WIN[c]] > 0
      res << WIN[c]
      me[WIN[c]] -= 1
      other[c] -= 1
      wins += 1
    else
      left = me.select { |k, v| !v.zero? }.keys
      to_play = left.min do |non_win|
        other[WIN[non_win]]
      end
      res << to_play
      me[to_play] -= 1
      other[c] -= 1
    end
  end
  wins >= (n / 2.0).ceil ? "YES\n#{res.join('')}" : "NO"
  # res.size == seq.size ? "YES\n#{res.join('')}" : "NO"
end

gets.strip.to_i.times do
  n = gets.strip.to_i
  a, b, c = gets.strip.split(' ').map(&:to_i)
  seq = gets.strip.split('')
  puts solve(n, a, b, c, seq)
end


Alice and Bob are playing a game on an array $$$a$$$ of $$$n$$$ positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If $$$a_1 = 0$$$, the player loses the game, otherwise: Player chooses some $$$i$$$ with $$$2\le i \le n$$$. Then player decreases the value of $$$a_1$$$ by $$$1$$$ and swaps $$$a_1$$$ with $$$a_i$$$. Determine the winner of the game if both players play optimally.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$  — the elements of the array $$$a$$$. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, if Alice will win the game, output "Alice". Otherwise, output "Bob". You can output each letter in any case. For example, "alIcE", "Alice", "alice" will all be considered identical.

NoteIn the first testcase, in her turn, Alice can only choose $$$i = 2$$$, making the array equal $$$[1, 0]$$$. Then Bob, in his turn, will also choose $$$i = 2$$$ and make the array equal $$$[0, 0]$$$. As $$$a_1 = 0$$$, Alice loses.In the second testcase, once again, players can only choose $$$i = 2$$$. Then the array will change as follows: $$$[2, 1] \to [1, 1] \to [1, 0] \to [0, 0]$$$, and Bob loses.In the third testcase, we can show that Alice has a winning strategy.

gets.to_i.times do
    n=gets.to_i
    arr=gets.chomp.split.map(&:to_i)
    if arr[0]==arr.min
        puts "Bob"
    else
        puts "Alice"
    end
end


Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.

Print a single integer — the required sum modulo 109 + 7.

NoteThere are three non-empty subsets in the first sample test:,  and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.


The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

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

candidate_wins = Array.new(n+1){0}
#cities
(0...m).each do |i|
	arr = gets.chomp.split.map{|x| x.to_i}
	curr_winner = 0
	curr_max_votes = -1
	(0...n).each do |j|
		if arr[j] > curr_max_votes
			curr_max_votes = arr[j]
			curr_winner = j
		end
	end
	candidate_wins[curr_winner+1]+=1
end
overall_winner = 0
over_all_win = -1
(1..n).each do |i|
	if candidate_wins[i] > over_all_win
		overall_winner = i
		over_all_win = candidate_wins[i]
	end
end

puts overall_winner

#!/usr/bin/ruby
N,M=gets.to_i
A=$<.map{|e|e.split.map(&:to_i)}
h=Hash.new(0)
A.each{|e|h[e.each_with_index.map{|x,i|[-x,i]}.min[1]]+=1}
p h.min_by{|k,v|[-v,k]}[0]+1

n,m = gets.split(" ").map(&:to_i)
cand = [0]*n
for i in (1..m)
   li = gets.split(" ").map(&:to_i)
   cand[li.index(li.max)]+=1
end
puts cand.index(cand.max) + 1

n,m=gets.split.map &:to_i;c=[0]*n;m.times{l=gets.split.map &:to_i;c[l.index(l.max)]+=1};p c.index(c.max)+1

# http://codeforces.com/contest/570/problem/A
n, m = gets.chomp.split.map(&:to_i)
array = Array.new(n) { 0 }

m.times do
  votes = gets.chomp.split.map(&:to_i)
  max = votes.max

  array[votes.index(max)] += 1
end

max = array.max
puts array.index(max) + 1

n, m = gets.split(' ').map{|x| x.to_i}
res = []
m.times do |x|
	res[x] = gets.split.map{|x| x.to_i}
	res[x] = res[x].index(res[x].max)

end

count = []
for i in 0...n
	count[i] = res.count(i)
end

puts count.index(count.max)+1

n, m = gets.split(" ").map(&:to_i)
a = Array.new(n){0}
m.times{
  voices = gets.split(" ")
  best = 0
  voices.each_index { |i| best = voices[i].to_i>voices[best].to_i ? i : best}
  a[best] += 1
}
best = 0
a.each_index { |i| best = a[i]>a[best] ? i : best}
puts best+1

c=(0..100).map{0}
n,m=gets.split.map{|e| e.to_i}
m.times{
	x=gets.split.map{|e| e.to_i}
	c[x.index(x.max)+1]+=1
}
p c.index(c.max)

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| [city_winners.count(i),-i] }+1

n,m = gets.split.map(&:to_i)
a = Array.new(n,0)
x,y = -1,0
m.times do |j|
	t = gets.split.map(&:to_i)
	for i in 0...n
		if t[i] > x
			x = t[i]
			y = i
		end
	end
	a[y] += 1
	x,y = -1,0
end
for i in 0...n
	if a[i] > x
		x = a[i]
		y = i
	end
end
p y+1

n, m = gets.chomp.split("\s").map(&:to_i)
a = m.times.map { gets.chomp.split("\s").map(&:to_i) }

winners = a.map do |votes_by_city|
  votes_by_city.find_index(votes_by_city.max)
end

puts winners.sort.max_by { |e| winners.count(e) } + 1

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

vt = Array.new(n) { 0 }
max_votes = 0
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        if i < max
            #pass
        elsif i == max
            maxs << index
        else
            maxs.clear
            max = i
            maxs << index
        end
    }
    vt[maxs.first] += 1
    if max_votes < vt[maxs.first]
        max_votes = vt[maxs.first]
    end
}
for index in 0...n
    if max_votes == vt[index]
        puts (index + 1) # 1-based index
        break
    end
end

n, m = gets.split(' ').map(&:to_i)
votes_in_cities = Array.new(n, 0)
m.times do
  tmp = gets.split(' ').map(&:to_i)
  vinner_in_city = tmp.index(tmp.max)
  votes_in_cities[vinner_in_city] += 1
end

puts votes_in_cities.index(votes_in_cities.max) + 1

n, m = gets.split.map(&:to_i)
a = m.times.map{gets.split.map(&:to_i)}
b = a.map{|x| x.index(x.max)}.sort
puts b.group_by{|x| x}.to_a.max_by{|x| x[1].length}[0] + 1

n, m = gets.split.map{|x| x.to_i}
c = [0]*n
m.times do
    a = gets.split.map{|x| x.to_i}
    c[a.find_index(a.max)] += 1
end
puts(c.find_index(c.max) + 1)

n, m = gets.chomp.split(' ').map { |i| i.to_i }
selected = []
count = Array.new(if n > m then n else m end) { |i| i = 0 }

m.times do
	candidates = gets.chomp.split(' ').map { |i| i.to_i }
	# find Max, put in array
	selected << candidates.index(candidates.max)
end

selected.each do |v|
	count[v] = selected.count(v)
end

puts count.index(count.max) + 1

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

candidate_wins = Array.new(n+1){-1}
#cities
(0...m).each do |i|
	arr = gets.chomp.split.map{|x| x.to_i}
	curr_winner = -1
	curr_max_votes = -1
	(0...n).each do |j|
		if arr[j] > curr_max_votes
			curr_max_votes = arr[j]
			curr_winner = j
		end
	end
	candidate_wins[curr_winner+1]+=1
end
overall_winner = -1
over_all_win = 0
(1..n).each do |i|
	if candidate_wins[i] > over_all_win
		overall_winner = i
		over_all_win = candidate_wins[i]
	end
end

puts overall_winner

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| [city_winners.count(i),-i] }[0]+1

def read_ints; gets.chomp.split.map(&:to_i) end
n,m = read_ints
city_winners = []
m.times do
	city_winners<<read_ints.each_with_index.max_by(&:first)[1]
end
puts city_winners.uniq.max_by{ |i| city_winners.count( i ) }+1

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

# 1st
vt = Array.new(n) { 0 }
vt2 = Array.new(n) { 0 }
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        vt[index] += i
        if max < vt[index]
            maxs.clear
            max = vt[index]
            maxs << index
        elsif max == vt[index]
            maxs << index
        else
            # pass
        end
    }
    vt2[maxs.pop] += 1
}

max_vote = vt2.max
for index in 0...n
    if vt2[index] == max_vote
        puts (index + 1) # 1-based index
        break
    end
end

# coding: utf-8

n, m = gets.split.map(&:to_i) # n candidates, m cities
votes = []
m.times {
    votes << gets.split.map(&:to_i)
}

# 1st
vt = Array.new(n) { 0 }
vt2 = Array.new(n) { 0 }
votes.each { |row|
    max, maxs = 0, []
    row.each_with_index { |i, index|
        vt[index] += i
        if max < vt[index]
            maxs.clear
            max = vt[index]
            maxs << index
        elsif max == vt[index]
            maxs << index
        else
            # pass
        end
    }
    vt2[maxs.first] += 1
}

max_vote = vt2.max
for index in 0...n
    if vt2[index] == max_vote
        puts (index + 1) # 1-based index
        break
    end
end

n, m = gets.split.map(&:to_i)
a = m.times.map{gets.split.map(&:to_i)}
b = a.map{|x| x.index(x.max)}
puts b.group_by{|x| x}.to_a.max_by{|x| x[1].length}[0] + 1


When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types:   transform lowercase letters to uppercase and vice versa;  change letter «O» (uppercase latin letter) to digit «0» and vice versa;  change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.

The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50  — the login itself. The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins. The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.

Print «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it. Otherwise print «No» (without quotes).

NoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one.

def simplify(string)
	str_arr = string.split("")
	str_copy = str_arr
	str_arr.each_with_index do |char, index|
		case char
		when 'O', 'o'	#big ou
			str_copy[index] = 0
		when 'l', 'I', 'L', 'i'
			str_copy[index] = 1
		else
			str_copy[index] = char
		end
	end
	str_copy.join('').downcase
end

wanted_login = gets.chomp
number = gets.chomp
logins = []

if wanted_login.length <= 50 && (number.to_i >= 1 && number.to_i <= 1000)
	all_logins_passed = true

	number.to_i.times do
		if all_logins_passed
			logins << gets.chomp
		end
	end

	logins.each do |curent_login|
		all_logins_passed = false if curent_login.length > 50
	end

	if all_logins_passed
		user_can_register = true

		logins.each do |existed_login|
			if simplify(existed_login).eql? simplify(wanted_login)
				user_can_register = false
			end
		end

		puts 'Yes' if user_can_register
		puts 'No' unless user_can_register
	end
end

def get_login
  s = gets
  s.gsub(/0{1}/, 'o').gsub(/[lLIi]{1}/, '1').downcase
end

new_login = get_login
n = gets.to_i
n.times do
  if new_login == get_login
    puts 'No'
    exit
  end
end

puts 'Yes'

def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("i", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def modify(s)
    s.gsub!("1", "l")
    s.gsub!("I", "l")
    s.gsub!("0", "o")
    s.downcase!
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def modify(s)
    s.gsub!("1", "l")
    s.gsub!("i", "l")
    s.gsub!("0", "o")
    s.downcase!
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def simplify(string)
	str_arr = string.split("")
	str_copy = str_arr
	str_arr.each_with_index do |char, index|
		case char
		when 'O', 'o'	#big ou
			str_copy[index] = 0
		when 'l', 'I', 'L', 'i'
			str_copy[index] = 1
		else
			str_copy[index] = char
		end
	end
	str_copy.join('').downcase
end

wanted_login = gets.chomp
number = gets.chomp
logins = []

if wanted_login.length <= 50 && (number.to_i > 1 && number.to_i < 1000)
	all_logins_passed = true

	number.to_i.times do
		if all_logins_passed
			logins << gets.chomp
		end
	end

	logins.each do |curent_login|
		all_logins_passed = false if curent_login.length > 50
	end

	if all_logins_passed
		user_can_register = true

		logins.each do |existed_login|
			if simplify(existed_login).eql? simplify(wanted_login)
				user_can_register = false
			end
		end

		puts 'Yes' if user_can_register
		puts 'No' unless user_can_register
	end
end

def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("I", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"

def modify(s)
    s.downcase!
    s.gsub!("1", "l")
    s.gsub!("0", "o")
end

s = gets.chomp
modify(s)

logins = Array.new
n = gets.chomp.to_i
for i in 1..n
    logins.push(gets.chomp)
    modify(logins.last)
end

for login in logins
    if login == s
        puts "No"
        exit
    end
end

puts "Yes"


You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.

Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.

n = gets.to_i
m = n / 3
a = gets.chomp.chars.map(&:to_i)
cnt = (0...3).map { a.count(_1) }

2.times do
	a.each_with_index do |from, i|
		(0...from).each do |to|
			if cnt[from] > m && cnt[to] < m
				a[i] = to
				cnt[from] -= 1
				cnt[to] += 1
				break
			end
		end
	end
	a = a.reverse.map { 2 - _1 }
	cnt.reverse!
end
puts a.join

n = gets.to_i
s = gets.chomp.split("").map(&:to_i)
a = [0,0,0]
n.times do |i|
    a[s[i]] += 1
end
if a[0] < n/3
    n.times do |i|
        next if s[i] == 0 || a[s[i]] <= n/3
        a[0] += 1
        a[s[i]] -= 1
        s[i] = 0
        break if a[0] == n/3
    end
end
if a[1] < n/3
    n.times do |i|
        next if s[i] < 2
        a[1] += 1
        a[2] -= 1
        s[i] = 1
        break if a[1] == n/3
    end
end
if a[2] < n/3
    n.times do |i|
        next if s[-1-i] == 2 || a[s[-1-i]] <= n/3
        a[2] += 1
        a[s[-1-i]] -= 1
        s[-1-i] = 2
        break if a[2] == n/3
    end
end
if a[1] < n/3
    n.times do |i|
        next if s[-1-i] > 0
        a[1] += 1
        a[0] -= 1
        s[-1-i] = 1
        break if a[1] == n/3
    end
end
puts s.join("")


At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \le m \le 10^9$$$) — the price of the item.

For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$ — the maximum possible non-negative integer.

gets.to_i.times { m = gets.strip; puts m.to_i - 10 ** (m.size - 1)}

n = gets.to_i

n.times do
  m = gets.chomp

  p (m.to_i - (10 ** (m.size - 1)))
end

def round_down_price(num)
  len = num.digits.count
  round = 10**(len-1)
  extra = num - round
  extra
end

t = gets.chomp.to_i
input = []
(0..t-1).each do |i|
  input.push(gets.chomp.to_i)
end

input.each do |i|
  p round_down_price(i)
end

t = gets.to_i
t.times {
  n = gets.chomp
  if n == 0
    puts "0"
  else
    n[0] = (n[0].ord - 1).chr
    puts n.to_i
  end
}

gets.to_i.times { m = gets; puts m.to_i - 10 ** (m.size - 1)}


One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

Output one integer — the number of different variants of group composition.

def comb(n,k)
	r=1
	k.times{|i|
		r=r*(n-i)/(i+1)
	}
	r
end
n=gets.to_i
p comb(n,5)+comb(n,6)+comb(n,7)


Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?

The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.

In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.

NoteIn the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
h = Hash.new

a.each_with_index do |e, i|
  (h[e] ||= []) << i
end

total = h.values.map(&:length).map { |e| [e, 2].min }.inject(:+)
half = total/2
puts half * (total-half)

b = Array.new(2*n)
cnt = 0

h.each do |k, v|
  if v.length >= 2
    b[v[0]] = 1
    b[v[1]] = 2
    cnt += 1
  end
end

h.each do |k, v|
  if v.length == 1
    if cnt < half
      b[v[0]] = 1
      cnt += 1
    else
      b[v[0]] = 2
    end
  end
end

a.each_with_index do |e, i|
  if b[i] == nil
    if cnt < n
      b[i] = 1
      cnt += 1
    else
      b[i] = 2
    end
  end
end

b.each do |e|
  print e , ' '
end
puts

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
c = Array.new(101) { [] }

a.each_with_index do |e, i|
  c[e] << i
end

total = c.map(&:length).map { |e| [e, 2].min }.inject(:+)
half = total/2
puts half * (total-half)

b = Array.new(2*n)
cnt = 0

c.each do |e|
  if e.length >= 2
    b[e[0]] = 1
    b[e[1]] = 2
    cnt += 1
  end
end

c.each do |e|
  if e.length == 1
    if cnt < half
      b[e[0]] = 1
      cnt += 1
    else
      b[e[0]] = 2
    end
  end
end

a.each_with_index do |e, i|
  if b[i] == nil
    if cnt < n
      b[i] = 1
      cnt += 1
    else
      b[i] = 2
    end
  end
end

b.each do |e|
  print e , ' '
end
puts

#!/usr/bin/ruby

n = $stdin.readline.to_i
cubes = $stdin.readline.split.map(&:to_i)

cubes_count = Hash.new

cubes.each{|x| cubes_count[x] = (cubes_count[x] == nil ? 1 : cubes_count[x] + 1 )}

a1 = []
a2 = []

cubes_count.each_pair {|key, value|
  if value == 1
    if a1.length < a2.length
      a1.push key
    else
      a2.push key
    end
  else
    a1.push key
    a2.push key
  end
}

a1.sort!
a2.sort!

b1 = a1.length
b2 = a2.length

cubes_count.each_pair {|key, value|
  v = value - 2
  while v > 1
    a1.push key
    a2.push key
    v -= 2
  end
  if v == 1
    if a1.length < a2.length
      a1.push key
    else
      a2.push key
    end
  end
}

# puts "#{cubes_count} #{a1.length} #{a2.length}"
# puts "#{a1}"
# puts "#{a2}"

ans = []

cubes.each_index { |i|
  if a1.include? cubes[i]
    ans[i] = 1
    a1.delete_at(a1.index(cubes[i]))
  else
    ans[i] = 2
    a2.delete_at(a2.index(cubes[i]))
  end
}

# puts ans.inject{|sum,x| sum + x }

puts "#{b1*b2}"
puts ans.join(' ')

n = gets.to_i
given = gets.split.map{|s| s.to_i}
numbers = Array::new(100, 0)
given.each { |cg| numbers[cg] += 1 }
flag0 = 0
flag1 = 0
sum = 0
numbers.map! {|n|
	if n > 0
		if n == 1
			sum += 1
			flag0 = (flag0+1)%2
			n = flag0
		elsif n%2 == 1
			sum += 2
			flag1 = (flag1+1)%2
			n += flag1
		else
			sum += 2
			n
		end
	end
}
if sum%2 == 0
	puts sum*sum/4
else
	puts sum/2*(sum/2 + 1)
end
given.each {|cg|
	print (numbers[cg]%2 + 1).to_s + " "
	numbers[cg] -= 1
}

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
h = Hash.new { |h, k| h[k] = [] }

a.each_with_index do |e, i|
  h[e] << i
end

tmp = h.values.map(&:length).map { |e| [e, 2].min }.inject(:+)
puts tmp/2*(tmp-tmp/2)

b = Array.new(2*n)
cnt = 0
a.each_with_index do |e, i|
  if b[i] == nil
	b[i] = 1
	h[e].shift
	if !h[e].empty?
	  b[h[e].pop] = 2
	end
	cnt += 1
	if cnt == n
	  break
	end
  end
end

b.each do |e|
  print e ||= 2, ' '
end
puts

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
h = Hash.new

a.each_with_index do |e, i|
  (h[e] ||= []) << i
end

total = h.values.map(&:length).map { |e| [e, 2].min }.inject(:+)
half = total/2
puts half * (total-half)

b = Array.new(2*n)
cnt = 0
h.each do |k, v|
  if v.length >= 2
	b[v[0]] = 1
	b[v[1]] = 2
	cnt += 1
  end
end

a.each_with_index do |e, i|
  if b[i] != nil
	next
  else
	if cnt < n
	  b[i] = 1
	  cnt += 1
	else
	  b[i] = 2
	end
  end
end

b.each do |e|
  print e , ' '
end
puts

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
h = Hash.new

a.each_with_index do |e, i|
  (h[e] ||= []) << i
end

total = h.values.map(&:length).map { |e| [e, 2].min }.inject(:+)
half = total/2
puts half * (total-half)

b = Array.new(2*n)
cnt = 0
h.each do |k, v|
  if v.length >= 2
	b[v[0]] = 1
	b[v[1]] = 2
	cnt += 1
  end
end

a.each_with_index do |e, i|
  if b[i] != nil
	next
  else
	if cnt < half
	  b[i] = 1
	  cnt += 1
	else
	  b[i] = 2
	end
  end
end

b.each do |e|
  print e ||= 2, '  '
end
puts

#!/usr/bin/ruby

n = $stdin.readline.to_i
cubes = $stdin.readline.split.map(&:to_i)

cubes_count = Hash.new

cubes.each{|x| cubes_count[x] = (cubes_count[x] == nil ? 1 : cubes_count[x] + 1 )}

a1 = []
a2 = []

cubes_count.each_pair {|key, value|
  v = value
  while v > 1
    a1.push key
    a2.push key
    v -= 2
  end
  if v == 1
    if a1.length < a2.length
      a1.push key
    else
      a2.push key
    end
  end
}

a1.sort!
a2.sort!

b1 = 1
b2 = 1

a1.each_index {|index|
  if index > 0
    if a1[index - 1] != a1[index]
      b1 += 1
    end
  end
}

a2.each_index {|index|
  if index > 0
    if a2[index - 1] != a2[index]
      b2 += 1
    end
  end
}

ans = []

cubes.each_index { |i|
  if a1.include? cubes[i]
    ans[i] = 1
    a1.delete_at(a1.index(cubes[i]) || a1.length)
  else
    ans[i] = 2
    a2.delete_at(a2.index(cubes[i]) || a2.length)
  end
}

puts "#{cubes_count}"
puts "#{a1}"
puts "#{a2}"
puts "#{b1*b2}"
puts ans.join(' ')

#!/usr/bin/ruby

n = $stdin.readline.to_i
cubes = $stdin.readline.split.map(&:to_i)

cubes_count = Hash.new

cubes.each{|x| cubes_count[x] = (cubes_count[x] == nil ? 1 : cubes_count[x] + 1 )}

a1 = []
a2 = []

cubes_count.each_pair {|key, value|
  v = value
  while v > 1
    a1.push key
    a2.push key
    v -= 2
  end
  if value == 1
    if a1.length < a2.length
      a1.push key
    else
      a2.push key
    end
  end
}

a1.sort!
a2.sort!

b1 = 1
b2 = 1

a1.each_index {|index|
  if index > 0
    if a1[index - 1] != a1[index]
      b1 += 1
    end
  end
}

a2.each_index {|index|
  if index > 0
    if a2[index - 1] != a2[index]
      b2 += 1
    end
  end
}

ans = []

cubes.each_index { |i|
  if a1.include? cubes[i]
    ans[i] = 1
    a1.delete_at(a1.index(cubes[i]) || a1.length)
  else
    ans[i] = 2
    a2.delete_at(a2.index(cubes[i]) || a2.length)
  end
}

# puts "#{cubes_count}"
# puts "#{a1}"
# puts "#{a2}"
puts "#{b1*b2}"
puts ans.join(' ')

#!/usr/bin/ruby

n = $stdin.readline.to_i
cubes = $stdin.readline.split.map(&:to_i)

cubes_count = Hash.new

cubes.each{|x| cubes_count[x] = (cubes_count[x] == nil ? 1 : cubes_count[x] + 1 )}

a1 = []
a2 = []

cubes_count.each_pair {|key, value|
  v = value
  while v > 1
    a1.push key
    a2.push key
    v -= 2
  end
  if v == 1
    if a1.length < a2.length
      a1.push key
    else
      a2.push key
    end
  end
}

a1.sort!
a2.sort!

b1 = 1
b2 = 1

a1.each_index {|index|
  if index > 0
    if a1[index - 1] != a1[index]
      b1 += 1
    end
  end
}

a2.each_index {|index|
  if index > 0
    if a2[index - 1] != a2[index]
      b2 += 1
    end
  end
}

ans = []

cubes.each_index { |i|
  if a1.include? cubes[i]
    ans[i] = 1
    a1.delete_at(a1.index(cubes[i]) || a1.length)
  else
    ans[i] = 2
    a2.delete_at(a2.index(cubes[i]) || a2.length)
  end
}

# puts "#{cubes_count}"
# puts "#{a1}"
# puts "#{a2}"
puts "#{b1*b2}"
puts ans.join(' ')


Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;  Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

In the single line print a single number — the answer to the problem.

NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

#f = File.open('test1.txt', 'r')
f = STDIN
n, l, r, Ql, Qr = f.gets.chomp.split.map &:to_i
w = f.gets.chomp.split.map &:to_i
sum = Array.new(w.size)
sum[0] = w[0]
(1...n).each do |i|
  sum[i] = sum[i-1] + w[i]
end

total = -1
(0..n).each do |k|
  tmp_total = 0
  tmp_sum = k == 0 ? 0 : sum[k-1]
  tmp_total += tmp_sum * l + (sum[n-1] - tmp_sum) * r
  if k > n - k
    tmp_total += (2 * k - n - 1) * Ql
  end
  if k < n - k
    tmp_total += (n - 2 * k - 1) * Qr
  end
  if total == -1
    total = tmp_total
  else
    total = [total, tmp_total].min
  end
end
puts total

n, l, r, ql, qr = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)

ans = 2**30
sl = 0
sr = a.inject(:+)

for i in (0..n)
  trial = 0
  if 2*i < n
    trial += (n-2*i-1)*qr
  elsif 2*i > n
    trial += (2*i-n-1)*ql
  end
  trial += sl*l + sr*r
  ans = [ans, trial].min
  if i < n
    sl += a[i]
    sr -= a[i]
  end
end

puts ans

n, l, r, ql, qr = gets.split.map(&:to_i)
w = gets.split.map(&:to_i)

left = Array.new(n+2, 0)
right = Array.new(n+2, 0)

for i in 0...n
  left[i+1] = left[i]+w[i]
  right[n-i] = right[n-i+1]+w[n-i-1]
end

min = 2**30
for i in 0..n
  energy = l*left[i]+r*right[i+1]
  same = n - 2*i
  if same > 1
    energy += (same-1)*qr
  elsif same < -1
    energy -= (same+1)*ql
  end
  if energy < min
    min = energy
  end
end

print min

n, l, r, ql, qr = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)

ans = 1e9
sl = 0
sr = a.inject(:+)

for i in (0..n)
  trial = 0
  if 2*i < n
    trial += (n-2*i-1)*qr
  elsif 2*i > n
    trial += (2*i-n-1)*ql
  end
  trial += sl*l + sr*r
  ans = [ans, trial].min
  if i < n
    sl += a[i]
    sr -= a[i]
  end
end

puts ans

line = gets.split(' ').map(&:to_i)
n = line[0]
l = line[1]
r = line[2]
ql = line[3]
qr = line[4]
a = gets.split(' ').map(&:to_i)
if l < r
  l, r = r, l
  ql, qr = qr, ql
end

a.sort!
ans = 2**32
sl = 0
sr = a.inject(:+)
for i in (0...a.size)
  trial = 0
  if 2*i > a.size
    break
  elsif 2*i < a.size
    trial += (a.size-2*i-1)*qr
  end
  trial += sl*l+sr*r
  ans = [ans, trial].min
  sl += a[i]
  sr -= a[i]
end

puts ans

n, l, r, ql, qr = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)

if l < r
  l, r = r, l
  ql, qr = qr, ql
end
a.sort!
ans = 2**32
sl = 0
sr = a.inject(:+)

for i in (0...a.size)
  trial = 0
  if 2*i > a.size
    break
  elsif 2*i < a.size
    trial += (a.size-2*i-1)*qr
  end
  trial += sl*l+sr*r
  ans = [ans, trial].min
  sl += a[i]
  sr -= a[i]
end

puts ans

n, l, r, ql, qr = gets.split.map(&:to_i)
w = gets.split.map(&:to_i)

left = Array.new(n+2, 0)
right = Array.new(n+2, 0)

for i in 0...n
  left[i+1] = left[i]+w[i]
  right[n-i] = right[n-i+1]+w[n-i-1]
end

min = 2**30
for i in 0..n
  energy = l*left[i]+r*right[i+1]
  same = n - 2*i
  if same > 0
    energy += same*qr
  else
    energy -= same*ql
  end
  if energy < min
    min = energy
  end
end

print min


You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of each test case consists of four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \leq a, b, c, d \leq 10^4$$$).

For each test case, output a single integer — the number of participants in front of Timur.

NoteFor the first test case, there are $$$2$$$ people in front of Timur, specifically the participants who ran distances of $$$3$$$ and $$$4$$$. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of $$$10000$$$ while all others ran a distance of $$$0$$$, $$$1$$$, and $$$2$$$ respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of $$$600$$$ while Timur ran a distance of $$$500$$$.

 gets.to_i.times {
 	a,*b = gets.split.map {|x| x.to_i }
 	puts  (b.count{|x| x > a})
 }

t = gets.to_i

inputs = []
(0...t).each do
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)
  inputs << arr

end

inputs.each do |arr|
  ans = 0
  # array.each do |arr|
    a = arr[0]
    b = arr[1]
    c = arr[2]
    d = arr[3]

    if a < b
      ans += 1
    end
    if a < c
      ans += 1
    end
    if a < d
      ans += 1
    end
  # end
  puts ans
end

s = gets.to_i

result = []
s.times do |i|
  a, b, c, d = gets.split(" ").map(&:to_i)

  r = 0
  r += 1 if b > a
  r += 1 if c > a
  r += 1 if d > a

  result.push(r)
end

result.each { |line| puts line }

t = gets.to_i
t.times do
    d=gets.split.map &:to_i
    puts d.count{|i|i>d[0]}
end

def solve
    v = gets.split.map(&:to_i)
    ans = 0
    if v[1] > v[0]
        ans = ans + 1
    end
    if v[2] > v[0]
        ans = ans + 1
    end
    if v[3] > v[0]
        ans = ans + 1
    end
    puts ans
end

gets.to_i.times do
    solve
end

gets.to_i.times do
  a, b, c, d = gets.split.map(&:to_i)
  ans = 0
  ans += 1 if a <= b
  ans += 1 if a <= c
  ans += 1 if a <= d
  puts ans
end

gets.to_i.times do
  a, b, c, d = gets.split.map(&:to_i)
  ans = 0
  ans += 1 if a < b
  ans += 1 if a < c
  ans += 1 if a < d
  puts ans
end

main = -> {
  t = int
  t.times do
      a, *x = ints

      puts x.count { _1 > a }
  end
}

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

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 ? 1 : 0] end
def YesNo t; puts $YesNo[t ? 1 : 0] end
def YESNO t; puts $YESNO[t ? 1 : 0] 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[]

gets.to_i.times do
  a, b, c, d = gets.split.map(&:to_i)
  p [b, c, d].count { |x| x > a }
end


You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the length of the array and its sum correspondingly.

For each test case, print the answer — the maximum possible value of $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.

NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$.

gets.to_i.times do
	a, b = gets.split.map(&:to_i)
	if a == 1
		puts 0
	elsif a == 2
		puts b
	else
		puts b * 2
	end
end

t = gets.to_i
until t==0 do
    n, m = gets.split.map(&:to_i)
    puts [2,n-1].min*m
    t-=1

end

t = gets.chomp.to_i
t.times do |testcase|
  (n,k) = gets.split.map(&:to_i)
  if n == 1
    puts 0
  elsif n == 2
    puts k
  else
    puts k*2
  end
end

t = gets.to_i

1.upto t do |i|
  sum = 0
  n, m = gets.split.map(&:to_i)
  if n == 1
    sum = 0
  elsif n == 2
    sum = m
  else
    sum = 2 * m
  end
  puts sum
end

gets.to_i.times {
  n, m = gets.split().map do |v|
    v.to_i
  end

  if n == 1
    puts 0
  elsif n == 2
    puts m
  else
    puts m * 2
  end
}

t=gets.chomp.to_i
while (t>0)
	n,m = gets.split.map(&:to_i)
	if(n==1)
		puts"0"
	elsif (n==2)
		puts"#{m}"
	else
		puts"#{m*2}"
	end
	t-=1
end

gets.to_i.times do
  n, m = gets.split.map &:to_i
  puts case n
  when 1
    0
  when 2
    m
  else
    2*m
  end
end

1.upto(gets.to_i) do
  n, m = gets.split(' ').map(&:to_i)

  k = n.div(2)
  l = m.div(k.zero? ? 1 : k)

  puts case n
       when 1
         0
       when 2
         m
       when proc(&:even?)
         2*m
       else
         2*l*k + 2*m.modulo(k)
       end
end

t = gets.to_i

(1).upto(t) do
  a = gets.split(' ').map(&:to_i)
  n = a[0]
  m = a[1]
  if n==1
    puts 0
  elsif n==2
    puts m
  else
    puts m*2
  end
end

t = gets.to_i
until t==0 do
    m, n = gets.split.map(&:to_i)
    puts [2,n-1].min*m
    t-=1

end


Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka:   $$$a$$$ was sorted in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$);  $$$n$$$ was even;  the following sequence $$$b$$$, consisting of $$$\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\frac n 2$$$ integers $$$b_1, b_2, \dots, b_{\frac n 2}$$$ ($$$0 \le b_i \le 10^{18}$$$) — sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

Print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$) in a single line. $$$a_1 \le a_2 \le \dots \le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.

n = gets.to_i
b = gets.split.map(&:to_i)
a1,a2 = [],[]
l,r = 0,10**18
b.each_with_index do |v,i|
  r = r < (v-l) ? r : v - l
  l = v - r
  a1 << l
  a2 << r
end
a1.each do |v|
  print "#{v} "
end
(n/2).times do |i|
  v = a2[-i-1]
  print "#{v}"
  print " " if i < (n/2-1)
end

def solve(n, b)
  mn, mx = 0, b[0]
  res = []
  b.each_with_index do |e, i|
    if mn + mx == e
      res[i] = mn
      res[b.size * 2 - i -1 ] = mx
    else
      if e - mn > mx
        res[b.size * 2 - i -1 ] = mx
        res[i] = e - mx
      else
        res[i] = mn
        res[b.size * 2 - i -1 ] = e - mn
      end
    end
    mn = res[i]
    mx = res[b.size * 2 - i -1 ]
  end
  res.join(' ')
end

puts solve(gets.strip.to_i, gets.strip.split.map(&:to_i))


After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

# http://codeforces.com/contest/525/problem/A

n = gets.to_i
s = gets.chomp.chars
keys = Hash.new(0)
ans = 0

s.each_slice(2) do |key, door|
  keys[key] += 1
  if keys[door.downcase] >= 1
    keys[door.downcase] -= 1
  else
    ans += 1
  end
end

puts ans

n = gets.chomp.to_i;
arr = gets.chomp.split("").map{|x| x.upcase.ord - 65;};
map = Array.new(26, 0);
ans = 0;

(n-1).times do |i|
  i = 2 * i;
  # print i, " ", arr[i], "\n";
  map[arr[i]] += 1;
  i += 1;
  map[arr[i]] -= 1;
  if map[arr[i]] == -1
    map[arr[i]] = 0;
    ans += 1;
  end
end
puts ans;

require 'pp'
def stdin_int; STDIN.gets.chomp.to_i; end
def stdin_ints; STDIN.gets.chomp.split(/ /).map(&:to_i); end

ans = 0

n = stdin_int
s = STDIN.gets.chomp
h = {}
h.default = 0
s.split(//).each_with_index do |c, index|
  if index.even?
    h[c] += 1
  else
    if h[c.downcase] > 0
      h[c.downcase] -= 1
    else
      ans += 1
    end
  end
end

puts ans

gets
hs=Hash.new(0)
ans=0
gets.chomp.chars{|e|
	e2=e.downcase
	if e2==e then
		hs[e]+=1
	else
		if hs[e2]>0 then
			hs[e2]-=1
		else
			ans+=1
		end

	end
}
puts ans

gets
a = gets.chomp.split(//)
has = Hash.new(0)
c = 0
a.each do |t|
  if t == t.downcase
    has[t] += 1
  elsif has[t.downcase] == 0
    c += 1
  else
    has[t.downcase] -= 1
  end
end

puts c

gets

answer = 0
stash = Hash.new { 0 }
gets.chomp.chars.each.with_index do |ch, i|
  if i % 2 == 0
    stash[ch.upcase] += 1
  else
    if stash[ch] > 0
      stash[ch] -= 1
    else
      answer += 1
    end
  end
end
puts answer

keys = Hash.new(0)
answer = 0
gets
gets.chomp.chars.each_slice(2) do |k,d|
  keys[k] += 1
  if keys[d.downcase] >= 1
    keys[d.downcase] -= 1
  else
    answer += 1
  end
end

puts answer

n = gets.to_i
a = gets.split("")
r = Array.new(123, 0)
ans = 0
a.each do |x|
  if x == x.downcase
    r[x.ord] += 1
  elsif x == x.upcase
    if r[x.downcase.ord] == 0
      ans += 1
    else
      r[x.downcase.ord] -= 1
    end
  end
end
puts ans

# f = File.open 'input.txt', 'r'
f = STDIN

def compute(n, s)
  missing_keys = 0
  keys = Hash.new(0)

  n.times do |i|
    break if i == n - 1
    # store the key
    keys[s[i * 2].upcase] += 1

    # unlock the door
    if keys[s[i * 2 + 1]].zero?
      missing_keys += 1
    else
      keys[s[i * 2 + 1]] -= 1
    end
  end
  missing_keys
end

while true
  raw_n = f.gets
  break unless raw_n
  n = raw_n.chomp.to_i
  s = f.gets.chomp
  p compute(n, s)
end

# http://codeforces.com/contest/525/problem/A

n = gets.to_i
s = gets.chomp.chars
keys = []
ans = 0

s.each_slice(2) do |key, door|
  keys << key
  if keys.include?(door.downcase)
    keys.delete key
  else
    ans += 1
  end
end

puts ans

# http://codeforces.com/contest/525/problem/A

n = gets.to_i
s = gets.chomp.chars
keys = Hash.new(0)
ans = 0

s.each_slice(2) do |key, door|
  keys[key] += 1
  if keys[door.downcase] > 0
    keys[key] -= 1
  else
    ans += 1
  end
end

puts ans

require 'pp'
def stdin_int; STDIN.gets.chomp.to_i; end
def stdin_ints; STDIN.gets.chomp.split(/ /).map(&:to_i); end

ans = 0

n = stdin_int
s = STDIN.gets.chomp
h = {}
h.default = 0
s.split(//).each_with_index do |c, index|
  if index.even?
    h[c] += 1
  else
    if h.has_key?(c.downcase)
      h[c] -= 1
    else
      ans += 1
    end
  end
end

puts ans

require 'pp'
def stdin_int; STDIN.gets.chomp.to_i; end
def stdin_ints; STDIN.gets.chomp.split(/ /).map(&:to_i); end

ans = 0

n = stdin_int
s = STDIN.gets.chomp
h = {}
s.split(//).each_with_index do |c, index|
  if index.even?
    h[c] = true
  else
    if h.has_key?(c.downcase)
      h.delete(c.downcase)
    else
      ans += 1
    end
  end
end

puts ans


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

n = gets.to_i
ar = (0...n).map{|x| x*(n+1)+1}
(0...n).reverse_each do |x|
  puts ar.map(&:to_s).join(" ")
  ar = ar.map(&:succ)
  ar[x] -= n
end

n=gets.to_i
a=[*1..n*n].each_slice(n).to_a.transpose
puts (a[0...n/2]+a[n/2..-1].map(&:reverse)).transpose.map{|e|e*' '}

n = gets.chomp.to_i
for i in 1..n
  l = ""
  for j in 1..n
    if j % 2 == 0
      l = l << ((j/2)*2*n-i+1).to_s << " "
    else
      l = l << (i+(j/2)*2*n).to_s << " "
    end
  end
  puts l
end

# -*- encoding: utf-8 -*-
n = gets.chomp.to_i

candies = (1 .. n ** 2).to_a
for i in 0 .. (n - 1) do
  array = []
  (n / 2).times do
    array << candies.shift
    array << candies.pop
  end
  puts array.join(" ")
end

n = STDIN.readline.to_i
lines = []
n.times do |r|
	c = 0
	parts = []
	n.times do |d|
		parts.push((r+d)%n * n + (c+d)%n + 1)
	end
	lines.push(parts.join(' '))
end
puts lines.join("\n")

n = gets.chomp.to_i
a = (1..(n*n)).to_a

a = a.each_slice(a.length/2).to_a
a.last.reverse!
a = a.first.zip(a.last)
puts a.each_slice(n/2).to_a.map{|x| x.flatten.join(' ')}

n=gets.to_i

for i in 0..n-1
	for j in 0..n/2-1
		print 1+(i*n/2)+j," "
	end
	for j in 0..n/2-1
		print n**2-n/2+1-(i*n/2)+j," "
	end
	if i!=n-1
		print "\n"
	end
end

#!/usr/bin/env ruby
n = gets.to_i
ind = 1
for i in 1..n
  str = ""
  for j in 0...n/2
    str += "#{ind} "
    str += "#{n*n+1 - ind} "
    ind += 1
  end
  puts str
end

#!/usr/bin/env ruby
n = gets.to_i
ind = 1
for i in 1..n
  str = ""
  for j in 0...n/2
    str += "#{ind + j} "
  end
  for j in 0...n/2
    str += "#{n*n+1 - ind} "
    ind += 1
  end
  puts str
end

#http://codeforces.com/problemset/problem/129/A

n = gets.to_i

initial_first  = 1
initial_last  = n**2

first = []
second = []
loop do
    first << initial_first
    first << initial_last
    initial_first += 2
    initial_last -= 2
    break if first.size >= n**2
end

first.each_with_index do |i,ind|
  print "#{i} "
  if (ind+1)%n ==0
    puts
  end
end

n =  gets.chomp.to_i

left = 1
right = n*n
(1..n).each do |i|
  (left..left+n/2-1).each { |i| print "#{i} " }
  (right-n/2+1..right).each { |i| print "#{i} " }
  left += n/2
  right -= n/2
  puts
end

arr = (1..gets.to_i ** 2).to_a
while arr.size != 0
  puts "#{arr.shift} #{arr.pop}"
end

n = gets.to_i
a = Array.new(n*n+1);
for i in 1..n*n do
    a[i] = i
  end
l = 0x0
l = 1
r = n*n
begin
  if (l>r) then break end
  printf("%d %d\n", a[l], a[r])
  l += 1
  r -= 1
end while true

n=gets.to_i
res=[]
x=1
n.times {|i|
    res<<[*x..x+n-1]
    res[i].reverse! if i.even?
    x+=n
}
n.times {|i|
    n.times{|j| print "#{res[j][i]} " }
    puts
}

# coding: utf-8

n = gets.to_i
base = [1]
np2 = n * n
while base.last < np2
     new_inc = base.last + (n + 1)
     base << new_inc
end

n.times {
    puts base.join(' ')
    #p "---> #{base.sum}"
    for i in 0...n
        base[i] = (base[i] + n)%np2
    end
}

%{
    먼저 1을 준비한다.
    n이 될때까지 n+1을 더한다.
    이렇게 만들어진 배열의 크기는 n과 같다. ---A
    이 배열의 합은 N = n*n (최대값)이라고 할 때
    (N*(N+1)/2)/n = n*(n*n + 1)/2 이다.
    n이 홀수라면 n*n도 홀수이므로 +1에서 짝수가 되어
    2로 나눌 수 있고, n이 짝수라면 두말할 필요없이 2로 나눠져
    저 결과값은 항상 정수를 유지한다. ----B
    A에서 만들어진 수열의 합은 B의 값과 같다.
    예를 들어 n = 3인 경우는 15, n = 4의 경우는 34이다.
    여기서부터 중요한데, A에서 만들어진 수열에 각각 아래의 연산을 취한다.
    A의 배열 원소를 An이라 할때,
    1) An 에 n을 더한다
    2) 1에 mod n*n 연산을 취해 나머지 값을 얻는다.
    이렇게 되면 항상 일정한 위치의 수끼리 합을 구하게 되므로 일정한 합계가 반복된다.
    이걸 n-1 회 반복하면 원하는 값들을 얻을 수 있다.
    예) n = 3
    step1) [1, 5, 9]
    step2) [4, 8, (3 + 9)%9] -> [4, 8, 3]
    step3) [7, (8 + 3)%9, 6)] -> [7, 2, 6]
    step4) [(7 + 3)%9, 5, 9 ] -> [1, 5, 9] <==> step1

    근데 시발 왜 이게 되지?
}

def main()
	n=gets.chomp.to_i
	ar=Array.new(n){}
	for i in 0...n
		ar[i]=""
	end
	f=true
	j=1
	i=n*n
	while(j<=i)
		if f
			for k in 0...n
				ar[k]+=j.to_s+" "
				j+=1
			end
		else
			for k in 0...n
				l=n-k-1
				ar[l]+=j.to_s+" "
				j+=1
			end
		end
		f=!f
	end
	for i in 0...n
		puts ar[i]
	end
end
main()

n = gets.to_i; n=n*n
([(1..n/2).to_a] + [((n/2+1)..n).to_a.reverse]).transpose.each{|x| puts x.join(' ')}

n = gets.to_i
a = Array.new(n){|x| x += 1}
n.times do |i|
  b = []
  n.times do |j|
    b << n * j + a[(i + j) % n]
  end
  puts b.join(" ")
end

#16h26
n = gets

def run(n)
  r = n*n
  q = n/2
  n.times do |i|
    st = i*q
    s = (1+st...q+1+st).to_a
    b = (r-q+1-st...r+1-st).to_a
    puts "#{s.join(' ')} #{b.join(' ')}"
  end
end

while n != nil
  run(n.to_i)
  n = gets
end

n=gets.to_i
n.times do |i|
  n.times do |j|
    print(j*n+(j+i)%n+1, ' ')
  end
  puts
end

n = gets.to_i
puts (n**2).times.map(&:next).each_slice(n).each_with_index.map{|x, i| x.rotate i }.transpose.map{|x| x.join ' ' }

n = gets.to_i
n2 = n**2
n.times do |i|
  list = []
  (n/2).times do |j|
    list << i + 1 + j * n
    list << n2 - (i + j * n)
  end
  puts list.join(" ")
end

n=gets.to_i
a=[*1..n].each_slice(n).to_a.transpose
a[n/2..-1].map!(&:reverse)
puts a.transpose.map{|e|e*' '}

n=gets.to_i
a=[*1..n*n].each_slice(n).to_a.transpose
a[n/2..-1].map!(&:reverse)
puts a.transpose.map{|e|e*' '}

#http://codeforces.com/problemset/problem/129/A

n = gets.to_i

initial_first  = 1
initial_last  = n**2

first = []
second = []
n.times do
    first << initial_first
    first << initial_last
    initial_first += 2
    initial_last -= 2
end

second = first.shift(n)

puts first.join(' ')
puts second.join(' ')

#http://codeforces.com/problemset/problem/129/A

n = gets.to_i

initial_first  = 1
initial_last  = n**2

p initial_first
p initial_last

first = []
second = []
n.times do
    first << initial_first
    first << initial_last
    initial_first += 2
    initial_last -= 2
end

second = first.shift(n)

puts first.join(' ')
puts second.join(' ')

n = gets.to_i
([(1..n/2).to_a] + [((n/2+1)..n).to_a.reverse]).transpose.each{|x| puts x.join(' ')}

#16h26
n = gets

def run(n)
  r = n*n
  q = n/2
  n.times do |i|
    s = (i+1...i+q+1).to_a
    b = (r-i-q+1...r-i+1).to_a
    puts "#{s.join(' ')} #{b.join(' ')}"
  end
end

while n != nil
  run(n.to_i)
  n = gets
end


There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible. The second line features a sequence of integers a1, a2, ..., an (0 ≤ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.

Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.

NoteConsider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6.

n, k = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i).map{ |x| x-1}
dp = Array.new(n, 0)
for i in 0..(n-1)
    mx = -1
    if arr[i] != -1
        last = [arr[i]+k, i-k-1].max
        mx = [i+k, n-1].min
        dp[i] = dp[arr[i]]+[mx-last, 0].max
    else
        last = [-1, i-k-1].max
        mx = [i+k, n-1].min
        dp[i] = mx-last
    end
end

puts dp.join(' ')


You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ non-zero integers (i.e. $$$a_i \ne 0$$$). You have to calculate two following values:  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is negative;  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is positive;

The first line contains one integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — the number of elements in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$$$ — the elements of the sequence.

Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

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

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

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

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

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

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

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

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

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

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

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

n = inp[0]
t = inp
m = na(2,0)
m[0] = 0
f = 0
ff = 0
pos = neg = 0
t.each.with_index do |d,i|
  if(d < 0)
    m[0],m[1] = m[1],m[0]
    m[1] += 1
  else
    m[0] += 1
  end
  pos += m[0]
  neg += m[1]
end
puts "#{neg} #{pos}"

def number_of_products
  n = gets.chomp.to_i
  numbers = gets.chomp.split(" ").map(&:to_i)
  positive, negative, a, b = 0, 0, 0, 0
  numbers.each do |num|
    c, d = 0, 0
    if num > 0
      c, d = a+1, b
    else
      c, d = b, a+1
    end
    a, b = c, d
    positive += c
    negative += d
  end
  puts "#{negative} #{positive}"
end

number_of_products


Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.

NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.

t = gets.to_i

t.times do
  nxyd = gets.chomp.split(" ").map(&:to_i)
  n = nxyd[0]
  x = nxyd[1]
  y = nxyd[2]
  d = nxyd[3]
  if (x%d==y%d)
    ans = (x-y).abs/d
  else
    if (y%d==1)
      ans = ((x.to_f-1)/d).ceil + ((y.to_f-1)/d).ceil
      if (n%d==1)
        ans = [ans,((n.to_f-x)/d).ceil+((n.to_f-y)/d).ceil].min
      end
    elsif (n%d==y%d)
      ans = ((n.to_f-x)/d).ceil+((n.to_f-y)/d).ceil
    else
      ans = -1
    end
  end

  puts ans
end

gets.to_i.times{
	n,x,y,d=gets.split.map &:to_i
	r = Float::INFINITY
	(y-1)%d==0 && r=[r,(x+d-2)/d+(y-1)/d].min
	(n-y)%d==0 && r=[r,(n+d-x-1)/d+(n-y)/d].min
	(y-x)%d==0 && r=[r,(y-x).abs/d].min
	p r.is_a?(Integer) ? r : -1
}

n = gets.strip.to_i
res = []
n.times do
    len, start, finish, per = gets.strip.split.map(&:to_i)

    if finish == start
        res << 0
        next
    end

    if (finish - start) % per == 0
        res << ((finish - start) / per).abs
    else
        from_start = (finish - 1) % per == 0
        from_end = (len - finish) % per == 0
        if from_start || from_end
            f_s = ((start.to_f/per).ceil + ((finish - 1) / per)).abs
            f_e = (((len - start).to_f / per).ceil + ((len - finish) / per)).abs
            r = 0
            if from_start && from_end
                if f_s > f_e
                    r = f_e
                else
                    r = f_s
                end
            else
                if from_start
                    r = f_s
                else
                    r = f_e
                end
            end
            r = 1 if r == 0
            res << r
        else
            res << -1
        end
    end
end

n.times do |x|
    p res[x]
end

def number_of_steps(crt, target, step)
  ((target - crt).abs.to_f / step).ceil
end

def exact_number_of_steps(crt, target, step)
  (target - crt).abs % step == 0 && number_of_steps(crt, target, step)
end

def min_steps(max, crt, target, step)
  exact = exact_number_of_steps(crt, target, step)
  return exact if exact

  via_beginning = [number_of_steps(crt, 1, step), exact_number_of_steps(1, target, step)]
  via_end = [number_of_steps(crt, max, step), exact_number_of_steps(max, target, step)]

  possibilities = []
  possibilities << via_beginning[0] + via_beginning[1] if via_beginning[1]
  possibilities << via_end[0] + via_end[1] if via_end[1]

  possibilities.min || -1

end

def solution
  test_cases = read_int

  test_cases.times do
    max, crt, target, step = read_ints
    puts min_steps(max, crt, target, step)
  end

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

gets.to_i.times do
    n,x,y,d=gets.split.map &:to_i
    if (x-y).abs%d==0
        puts (x-y).abs/d
    else
        a=nil
        a=(x-1+d-1)/d+(y-1+d-1)/d if (y-1)%d==0
        b=nil
        b=(n-x+d-1)/d+(n-y+d-1)/d if (n-y)%d==0
        if a && b
            puts [a, b].min
        elsif a
            puts a
        elsif b
            puts b
        else
            puts -1
        end
    end
end

t = gets.to_i

1..t.times do
  n, start, fin, k = gets.split.map(&:to_i)

  if (fin-start) % k == 0
    puts ((fin-start)/k).abs
  else
    ans = 9999999999
    if (fin-1)%k==0
        ans = (fin-1)/k + ((start-1)/k.to_f).ceil
    end

    if (n-fin)%k==0
        ans = [ans, (n-fin)/k + ((n-start)/k.to_f).ceil].min
    end

    if ans == 9999999999
        puts -1
    else
        puts ans
    end
  end
end

t = gets.to_i
t.times do
    n, x, y, d = gets.split.map{|x| x.to_i}
    x, y = y, x if x > y
    a = []
    a << (y - x)/d if (y - x)%d == 0
    a << (y - 1)/d + (x - 1 + d - 1)/d if (y - 1)%d == 0
    a << (n - y)/d + (n - x + d - 1)/d if (n - y)%d == 0
    puts(a.min || -1)
end

t = gets.to_i

t.times do
  nxyd = gets.chomp.split(" ").map(&:to_i)
  n = nxyd[0]
  x = nxyd[1]
  y = nxyd[2]
  d = nxyd[3]
  if (x%d==y%d)
    ans = (x-y).abs/d
  else
    if (y%d==1)
      ans = ((x.to_f-1)/d).ceil + ((y.to_f-1)/d).ceil
      if (n%d==1)
        ans = [ans,((n.to_f-x)/d).ceil+((y.to_f-1)/d).ceil].min
      end
    elsif (n%d==y%d)
      ans = ((n.to_f-x)/d).ceil+((y.to_f-1)/d).ceil
    else
      ans = -1
    end
  end

  puts ans
end

gets.to_i.times{
	n,x,y,d=gets.split.map &:to_i
	r = Float::INFINITY
	(y-1)%d==0 && r=[r,(x+d-2)/d+(y-1)/d].min
	(n-y)%d==0 && r=[r,(x+d-x-1)/d+(n-y)/d].min
	(y-x)%d==0 && r=[r,(y-x).abs/d].min
	p r.is_a?(Integer) ? r : -1
}

n = gets.strip.to_i
res = []
n.times do
    len, start, finish, per = gets.strip.split.map(&:to_i)

    if finish == start
        res << 0
        next
    end

    if (finish - start) % per == 0
        res << ((finish - start) / per).abs
    else
        from_start = (finish - 1) % per == 0
        from_end = (len - finish) % per == 0
        if from_start || from_end
            f_s = ((finish.to_f/per).floor + ((finish - 1) / per)).abs
            f_e = (((len - start).to_f / per).ceil + ((len - finish) / per)).abs
            r = 0
            if from_start && from_end
                if f_s > f_e
                    r = f_e
                else
                    r = f_s
                end
            else
                if from_start
                    r = f_s
                else
                    r = f_e
                end
            end
            r = 1 if r == 0
            res << r
        else
            res << -1
        end
    end
end

n.times do |x|
    p res[x]
end

n = gets.strip.to_i
res = []
n.times do
    len, start, finish, per = gets.strip.split.map(&:to_i)
    if (finish - start) % per == 0
        res << ((finish - start) / per).abs
    else
        from_start = (finish - 1) % per == 0
        from_end = (len - finish) % per == 0
        if from_start || from_end
            f_s = ((finish.to_f/per).floor + ((finish - 1) / per)).abs
            f_e = (((len - start).to_f / per).ceil + ((len - finish) / per)).abs
            if from_start && from_end
                if f_s > f_e
                    res << f_e
                else
                    res << f_s
                end
            else
                if from_start
                    res << f_s
                else
                    res << f_e
                end
            end
        else
            res << -1
        end
    end
end

n.times do |x|
    r = res[x]
    r = 1 if r == 0
    p r
end


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

n = gets.chomp
arr= gets.split().map(&:to_i)
arr.sort!
min_val =arr.min
max_val = arr.max
count = 0
arr.each{|i| if i>min_val and i<max_val then count+=1;end}
puts count

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i).sort
i = 1
min_s = a[0]
max_s = a[n - 1]
ans = 0
while i < n - 1
    ans += 1 if min_s < a[i] && a[i] < max_s
    i += 1
end
puts ans

h=Hash.new(0)
n=gets.to_i
x=gets.split.map{|e| e.to_i}.sort
x.each{|e|
	h[e]+=1
}
x=h.to_a
x.pop
x.shift
ans=0
x.each{|e|
	ans+=e[1]
}
puts ans

# coding: utf-8

n = gets.to_i
ad = {}
gets.split.each { |i|
    i = i.to_i
    ad[i] ||= 0
    ad[i] += 1
}
sorted_keys = ad.keys.sort

if ad.length <= 2
    puts "0"
else
    puts n - (ad[sorted_keys.first] + ad[sorted_keys.last])
end

#!/usr/bin/env ruby

stewards_count = gets.to_i
stewards_values = gets.split.map(&:to_i)

#
max = min = stewards_values.first
stewards_map = Hash.new(0)
stewards_values.each do |v|
  stewards_map[v] += 1
  min = v if v < min
  max = v if v > max
end

count = 0
(stewards_map.keys - [min, max]).each do |v|
  count += stewards_map[v]
end

puts count

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

arr=[]
x.inject(x[0]){|e1,e2|
	arr<<(e2-e1).abs
	e2
}
puts arr.count{|e| e==1}

h=Hash.new(0)
n=gets.to_i
x=gets.split.map{|e| e.to_i}.sort
x.each{|e|
	h[e]+=1
}
x=h.to_a
x.pop
x.shift
p x.size

n=gets.to_i
x=gets.split.map{|e| e.to_i}.sort

arr=[]
x.inject(x[0]){|e1,e2|
	arr<<(e2-e1).abs
	e2
}
puts arr.count{|e| e==1}

h=Hash.new(0)
n=gets.to_i
x=gets.split.map{|e| e.to_i}.sort
x.each{|e|
	h[e]+=1
}
x=h.to_a
ans=0
x.inject(x[0]){|e1,e2|
	if e1[0]+1==e2[0] then
		ans+=e1[1]*e2[1]
	end
	e2
}
p ans

# coding: utf-8

n = gets.to_i
ad = {}
gets.split.each { |i|
    i = i.to_i
    ad[i] ||= 0
    ad[i] += 1
}

if ad.length - 2 <= 0
    puts "0"
else
    puts ad.length - 2
end


Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map.Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.Help Slava to destroy all tanks using as few bombs as possible.

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the size of the map.

In the first line print m — the minimum number of bombs Slava needs to destroy all tanks. In the second line print m integers k1, k2, ..., km. The number ki means that the i-th bomb should be dropped at the cell ki. If there are multiple answers, you can print any of them.

n=gets.to_i
x=(1..n).select(&:odd?)
y=(1..n).select(&:even?)
res=y+x+y
puts res.size, res*' '


You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.

The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i < b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.

Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).

NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.

input_1 = gets.split.map(&:to_i)
input_2 = gets.split.map(&:to_i)

b = input_1[0]
k = input_1[1]

b_flag = 0
k_flag = 0
odd_count = 0

if b % 2 == 0
  b_flag = 0
else
  b_flag = 1
end

for i in 0..k - 2 do
  if input_2[i] % 2 != 0
    odd_count += 1
  end
end

if b_flag == 0
  if input_2[k - 1] % 2 == 0
    puts "even"
  else
    puts "odd"
  end
else
  if odd_count % 2 == 0
    if input_2[k - 1] % 2 == 0
      puts "even"
    else
      puts "odd"
    end
  else
    if input_2[k - 1] % 2 == 0
      puts "odd"
    else
      puts "even"
    end
  end
end

b,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
if b%2 == 0
    ans ^= a[-1]%2
else
    for i in 0..k-1
        ans ^= a[i]%2
    end
end
puts (ans == 1 ? "odd" : "even")

DBG = true
b,k = gets.split.map{|z| z.to_i}
a = gets.split.map{|z| z.to_i}
if b%2 == 0
  iseven = (a[-1]%2 == 0)
else
  iseven = (a.inject(:+)%2 == 0)
end
puts (iseven ? "even" : "odd")

input_1 = gets.split.map(&:to_i)
input_2 = gets.split.map(&:to_i)

b = input_1[0]
k = input_2[1]

b_flag = 0
k_flag = 0
odd_count = 0

if b % 2 == 0
  b_flag = 0
else
  b_flag = 1
end

input_2.each do |num|
  if num % 2 != 0
    odd_count += 1
  end
end

if b_flag == 0
  puts "even"
else
  if odd_count % 2 == 0
    puts "even"
  else
    puts "odd"
  end
end


Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.A common divisor for two positive numbers is a number which both numbers are divisible by.But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range.You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.

The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109).

Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.

def search(x,res)
        lb=-1
        ub=res.length
        while ub-lb>1
                mid=(ub+lb)>>1
                if res[mid]<=x then
                        lb=mid
                else
                        ub=mid
                end
        end
        return ub
end

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

res=[]
for i in 1..a
        if i*i>a then
                break
        end
        if a%i ==0 then
                if b%i==0 then
                        res.push(i)
                end
        end
end
for i in 1..a
        if i*i>=a then
                break
        end
        if a%i ==0 then
                if b%(a/i)==0 then
                        res.push(a/i)
                end
        end
end
res.sort!

#p res
#p search(2,res)
q=gets.to_i
(1..q).each{
        input=gets.split.map(&:to_i)
        x=res[search(input[1],res)-1]
        if x>=input[0] then
                puts x
        else
                puts -1
        end
}

def r()
   gets.split().map(&:to_i)
end
a,b = r()
q = gets.to_i
g = a.gcd(b)
d = []
i = 1
while i*i<=g do
  d+=[i, g/i] if g%i==0
  i+=1
end
d.sort!
for i in (0..q-1)
  l,r=r()
  a = d.reject{|e| e>r}[-1]
  a = -1 if a<l
  print "#{a}\n"
end

a,b = gets.split().map(&:to_i)
q = gets.to_i
g = a.gcd(b)
d = []
i = 1
while i*i<=g do
  if g%i==0
    d<< i
    d<< g/i
  end
  i+=1
end
d.sort!
for i in (0..q-1)
  l,r=gets.split(' ').map(&:to_i)
  a=0
  for i in d
    if i<=r
      a = i
    else
      break
    end
   end
   print "#{a}\n" if a>=l
   print "-1\n" if a<l
end

a,b = gets.split().map(&:to_i)
q = gets.to_i
g = a.gcd(b)
d = []
i = 1
while i*i<=g do
  d+=[i, g/i] if g%i==0
  i+=1
end
d.sort!
for i in (0..q-1)
  l,r=gets.split(' ').map(&:to_i)
  a=0
  for i in d
      a = i  if i<=r
  end
  a = -1 if a<l
  print "#{a}\n"
end

def r()
   gets.split().map(&:to_i)
end
a,b = r()
q = gets.to_i
g = a.gcd(b)
d = []
i = 1
while i*i<=g do
  d+=[i, g/i] if g%i==0
  i+=1
end
d.sort!
for i in (0..q-1)
  l,r=r()
  a=0
  for i in d
      a = i  if i<=r
  end
  a = -1 if a<l
  print "#{a}\n"
end

def divisors(n)
  factors = Hash.new(0).tap do |f|
    d = 1
    2.step(n, d).each do |i|
      break if i * i > n
      while n % i == 0
        n /= i
        f[i] += 1
      end
      d = 2
    end
    f[n] += 1 unless n == 1
  end.to_a

  [].tap do |ret|
    f = lambda do |i, r|
      if i == factors.size
        ret << r
        return
      end
      (factors[i][1] + 1).times do
        f.call(i + 1, r)
        r *= factors[i][0]
      end
    end
    f.call(0, 1)
  end
end

a, b = gets.chomp.split.map{|s| s.to_i}
cds = (divisors(a) & divisors(b)).sort
ret = []
gets.to_i.times do
  result = -1
  r = gets.chomp.split.map{|s| s.to_i}
  min, max = 0, cds.size - 1
  n = r[1]
  while min <= max
    mid = (min + max) / 2
    if n == cds[mid]
      min = mid
      break
    elsif n < cds[mid]
      max = mid - 1
    else
      min = mid + 1
    end
  end
  i =  min
  i -= 1 unless cds[i] == r[1]
  if cds[i] < r[0]
    ret << -1
  else
    ret << cds[i]
  end
end
ret.each{|s| puts s}

def factors(n)
  Hash.new(0).tap do |factors|
    d = 1
    2.step(n, d).each do |i|
      next if i * i > n
      while n % i == 0
        n /= i
        factors[i] += 1
      end
      d = 2
    end
    factors[n] += 1 unless n == 1
  end.to_a
end

def divisors(factors)
  [].tap do |ret|
    f = lambda do |i, r|
      if i == factors.size
        ret << r
        return
      end
      (factors[i][1] + 1).times do
        f.call(i + 1, r)
        r *= factors[i][0]
      end
    end
    f.call(0, 1)
  end
end

def bsearch(array, n)
  min, max = 0, array.size - 1
  while min <= max
    mid = (min + max) / 2
    if n == array[mid]
      return mid
    elsif n < array[mid]
      max = mid - 1
    else
      min = mid + 1
    end
  end
  return min
end

a, b = gets.chomp.split.map{|s| s.to_i}
cds = divisors(factors(a)) & divisors(factors(b))
ret = []
gets.to_i.times do
  result = -1
  r = gets.chomp.split.map{|s| s.to_i}
  i = bsearch(cds, r[1])
  i -= 1 unless cds[i] == r[1]
  if cds[i] < r[0]
    ret << -1
  else
    ret << cds[i]
  end
end
ret.each{|s| puts s}

require 'mathn'
a, b = gets.chomp.split.map{|s| s.to_i}
divisors = (2..[a,b].min).select do |i|
  a % i == 0 && b % i == 0
end
ret = []
gets.to_i.times do
  i = gets.chomp.split.map{|s| s.to_i}
  if n = divisors.detect{|d| (i[0]..i[1]).to_a.include?(d)}
    ret << n
  else
    ret << -1
  end
end
ret.each{|i| puts i}

def bsearch(array, n)
  min, max = 0, array.size - 1
  while min <= max
    mid = (min + max) / 2
    if n == array[mid]
      return mid
    elsif n < array[mid]
      max = mid - 1
    else
      min = mid + 1
    end
  end
  return min
end
a, b = gets.chomp.split.map{|s| s.to_i}
divisors = [1]
(2..(a > b ? b : a)).each do |i|
  divisors << i if a % i == 0 && b % i == 0
end
ret = []
gets.to_i.times do
  result = -1
  r = gets.chomp.split.map{|s| s.to_i}
  if divisors.last < r[0]
  elsif r[1] < divisors.first
  end
  i = bsearch(divisors, r[1])
  i -= 1
  if divisors[i] < r[0]
    ret << -1
  else
    ret << divisors[i]
  end
end
ret.each{|i| puts i}


You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \cdot a_j = i + j$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \cdot a_j = i + j$$$.

NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.

t = gets.to_i
t.times{ |x|
  n = gets.to_i
  res = 0
  m = n + n -1
  arr = gets.chomp.split(" ").map(&:to_i)
  hs = Hash[(1..arr.length).zip arr].lazy.
    sort_by{|i, v| v}
  #p hs
  (0..m).each{ |i|
    j = i+1
    e = m/hs[i][1]
    #p j
    #p n
    #p j >= n
    break if j >= n or hs[j][1] > e
    while j < n and hs[j][1] <= e
      res += 1 if hs[i][1]*hs[j][1] == hs[i][0] + hs[j][0]

      j += 1
    end
  }
  puts res
}

gets.to_i.times do

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

  res = 0
  m = n + n -1
  hs = Hash[(1..arr.length).zip arr].lazy.
    sort_by{|i, v| v}

  (0..m).each do |i|
    j = i+1
    e = m/hs[i][1]
    break if j >= n or hs[j][1] > e
    while j < n and hs[j][1] <= e
      res += 1 if hs[i][1]*hs[j][1] == hs[i][0] + hs[j][0]

      j += 1
    end
  end
  puts res
end


You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$), $$$a_{x}+a_{y} \neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.

NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$.

t = gets.chomp.to_i
#p n
t.times do
    n = gets.chomp.to_i
    i = 0
    until n == i
        a = 1
        print a
        if i != n- 1
        print " "
        end
        i += 1
    end
    print "\n"
end

t = gets.to_i
t.times do
	n = gets.to_i
	puts "1 "*n
end

gets.to_i.times do
    res = ""
    gets.to_i.times do
        res += "1 "
    end
    puts res
end

gets.to_i.times { puts ([1] * gets.to_i).join(' ')  }