The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.

The first line contains a single integer n (2 ≤ n ≤ 105) — the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, — array a. Note that the elements of the array are not necessarily distinct numbers.

In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.

NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".

n = gets.to_i
a = gets.chomp.split.map(&:to_i)
b = a.sort
if a == b
  puts "YES"
  exit
end
count = 0
n.times do |i|
  count +=1 if a[i] != b[i]
end
puts count == 2 ? "YES" : "NO"

n = gets.to_i
a = gets.split.map &:to_i
b = a.sort
s = 0
a.zip(b).each do |x, y|
  s += x != y ? 1 : 0
end
puts s > 2 ? "NO" : "YES"

n = gets.to_i
ar = gets.split.map(&:to_i)
br = ar.sort

cnt = 0
n.times do |i|
	cnt += 1 if ar[i] != br[i]
end

puts (cnt >2 ? "NO":"YES")

STDIN.readline.to_i; numbers = STDIN.readline.split(' ').map { |x| x.to_i }
sorted = numbers.sort

count = 0
for i in 0..sorted.length
  count += 1 if sorted[i] != numbers[i]
end

if count <= 2; puts "YES"; else puts "NO"; end

n=gets.to_i
a=gets.split.map(&:to_i)
b=a.sort
pos=0
n.times{|i|pos+=1 unless a[i]==b[i]}
puts pos<3 ? "YES" : "NO"

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort
cnt = 0
for i in 0..n - 1 do
    cnt += 1 if a[i] != b[i]
end
puts "YES" if cnt <= 2
puts "NO" if cnt > 2

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

n = $stdin.gets.to_i
a = $stdin.gets.chomp.split.map(&:to_i)

c = a.zip(a.sort).count { |x, y| x != y }
puts (c <= 2 ? 'YES' : 'NO')

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
c = 0
sorted = arr.sort
arr.each_with_index do |a,i|
	c += 1 if a != sorted[i]
end
puts c <= 2 ? "YES" : "NO"

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
b = a.sort
cnt = 0
for i in 0...n
    if a[i] != b[i]
        cnt += 1
    end
end
if cnt <= 2
    puts 'YES'
else
    puts 'NO'
end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
c = 0
arr.each_with_index do |a,i|
	c += 1 if a != (i + 1 )
end
puts c <= 2 ? "YES" : "NO"


Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.  Determine if Pig can visit the friend using teleports only, or he should use his car.

The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house. The next n lines contain information about teleports. The i-th of these lines contains two integers ai and bi (0 ≤ ai ≤ bi ≤ m), where ai is the location of the i-th teleport, and bi is its limit. It is guaranteed that ai ≥ ai - 1 for every i (2 ≤ i ≤ n).

Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower).

NoteThe first example is shown on the picture below:  Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.The second example is shown on the picture below:  You can see that there is no path from Pig's house to his friend's house that uses only teleports.

n,m=gets.split.map &:to_i
last=0
n.times{
	a,b=gets.split.map &:to_i
	if a>last
		puts :NO
		exit
	else
		last=[b,last].max
		if last>=m
			puts :YES
			exit
		end
	end
}
puts :NO

n, m = gets.chomp.split.map(&:to_i)
pos = 0

for i in 1..n
  st, en = gets.chomp.split.map(&:to_i)
  if st > pos
    puts "NO"
    exit 0
  else
    pos = [pos, en].max
  end
end

if pos >= m
  puts "YES"
else
  puts "NO"
end

#!/bin/ruby

n, m = gets.strip.split(' ')
n = n.to_i
m = m.to_i
visiting = 'NO'
ps = 0
pd = 0
for i in (1..n)
    s, d = gets.strip.split(' ')
    s = s.to_i
    d = d.to_i
    if s.between? ps, pd
        ps = s
        pd = d if pd <= d
        if m.between? s, d
            visiting = 'YES'
            break
        end
    else
        visiting = 'NO'
        break
    end
end
puts visiting

n, m = gets.strip.split(' ').map(&:to_i)

a = []

n.times do
	a << gets.strip.split(' ').map(&:to_i)
end

max_till_now = 0

mp = Hash.new(nil)
bool = true
a.each do |x|
	mp[x[0]] = true
	mp[x[1]] = true
	if x[0] > max_till_now
		bool = false
		break
	else
		max_till_now = [x[1], max_till_now].max
	end
end

if !bool
	puts 'NO'
else
	if mp[m]
		puts 'YES'
	else
		puts 'NO'
	end
end

#!/bin/ruby

n, m = gets.strip.split(' ')
n = n.to_i
m = m.to_i
visiting = 'NO'
ps = 0
pd = 0
for i in (1..n)
    s, d = gets.strip.split(' ')
    s = s.to_i
    d = d.to_i
    if s.between? ps, pd
        ps = s
        pd = d
        if m.between? s, d
            visting = 'YES'
            break
        end
    else
        visting = 'NO'
        break
    end
end
puts visting

#!/bin/ruby

n, m = gets.strip.split(' ')
n = n.to_i
m = m.to_i
visiting = 'NO'
ps = 0
pd = 0
for i in (1..n)
    s, d = gets.strip.split(' ')
    s = s.to_i
    d = d.to_i
    if s.between? ps, pd
        ps = s
        pd = d
        if m.between? s, d
            visiting = 'YES'
            break
        end
    else
        visiting = 'NO'
        break
    end
end
puts visiting

#!/bin/ruby

n, m = gets.strip.split(' ')
n = n.to_i
m = m.to_i
ps = 0
pd = 0
for i in (1..n)
    s, d = gets.strip.split(' ')
    s = s.to_i
    d = d.to_i
    if s.between? ps, pd
        ps = s
        pd = d
        if m.between? s, d
            visting = 'YES'
            break
        end
    else
        visting = 'NO'
        break
    end
end
puts visting

#!/bin/ruby

n, m = gets.strip.split(' ')
n = n.to_i
m = m.to_i
ps = 0
pd = 0
for i in (1..n)
    s, d = gets.strip.split(' ')
    s = s.to_i
    d = d.to_i
    if pd.between? s, d
        pd = d
        if m.between? s, d
            visting = 'YES'
            break
        end
    else
        visting = 'NO'
        break
    end
end
puts visting

n, m = gets.strip.split(' ').map(&:to_i)

a = []

n.times do
	a << gets.strip.split(' ').map(&:to_i)
end

max_till_now = a[0][0]

mp = Hash.new(nil)
bool = true
a.each do |x|
	mp[x[0]] = true
	mp[x[1]] = true
	if x[0] > max_till_now
		bool = false
		break
	else
		max_till_now = [x[1], max_till_now].max
	end
end

if !bool
	puts 'NO'
else
	if mp[m]
		puts 'YES'
	else
		puts 'NO'
	end
end

n, m = gets.strip.split(' ').map(&:to_i)

a = []

n.times do
	a << gets.strip.split(' ').map(&:to_i)
end

max_till_now = a[0][0]

mp = Hash.new(0)
bool = true
a.each do |x|
	mp[x[0]] = true
	mp[x[1]] = true
	if x[0] > max_till_now
		bool = false
		break
	else
		max_till_now = [x[1], max_till_now].max
	end
end

if !bool
	puts 'NO'
else
	if mp[m]
		puts 'YES'
	else
		puts 'NO'
	end
end

n, m = gets.strip.split(' ').map(&:to_i)

a = []

n.times do
	a << gets.strip.split(' ').map(&:to_i)
end

max_till_now = 0

mp = Hash.new(0)
bool = true
a.each do |x|
	mp[x[0]] = true
	mp[x[1]] = true
	if x[0] > max_till_now
		bool = false
		break
	else
		max_till_now = [x[1], max_till_now].max
	end
end

if !bool
	puts 'NO'
else
	if mp[m]
		puts 'YES'
	else
		puts 'NO'
	end
end


We're giving away nice huge bags containing number tiles! A bag we want to present to you contains $$$n$$$ tiles. Each of them has a single number written on it — either $$$1$$$ or $$$2$$$.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!

The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the number of number tiles in the bag. The following line contains $$$n$$$ space-separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{1, 2\}$$$) — the values written on the tiles.

Output a permutation $$$b_1, b_2, \dots, b_n$$$ of the input sequence $$$(a_1, a_2, \dots, a_n)$$$ maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.

NoteThe first solution produces the prefix sums $$$1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}}$$$ (four primes constructed), while the prefix sums in the second solution are $$$1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}}$$$ (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.

n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0,0] # 1,2
a.each do |v|
  cnt[v-1] += 1
end

if cnt[0] == 0
  print "2"
  (cnt[1]-1).times do
    print " 2"
  end
elsif cnt[1] == 0
  print "1"
  (cnt[0]-1).times do
  print " 1"
  end
elsif cnt[0] % 2 == 1
  print "2"
  cnt[0].times do
    print " 1"
  end
  (cnt[1]-1).times do
    print " 2"
  end
elsif cnt[0] % 2 == 0
  print "2 1"
  (cnt[1]-1).times do
    print " 2"
  end
  (cnt[0]-1).times do
    print " 1"
  end
end


In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.

The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.

For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.

NoteThe picture corresponds to the first example test case.  When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.

N = gets.to_i
ps = [0] + gets.split.map(&:to_i)

hole = Array.new(N+1)
ans = []
(1..N).each do |i|
    (1..N).each do |j|
        hole[j] = nil
    end
    loop do
        hole[i] = true
        i = ps[i]
        if hole[i]
            ans.push(i)
            break
        end
    end
end
puts ans.join(' ')


There was a string $$$s$$$ which was supposed to be encrypted. For this reason, all $$$26$$$ lowercase English letters were arranged in a circle in some order, afterwards, each letter in $$$s$$$ was replaced with the one that follows in clockwise order, in that way the string $$$t$$$ was obtained. You are given a string $$$t$$$. Determine the lexicographically smallest string $$$s$$$ that could be a prototype of the given string $$$t$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter, that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$t$$$. The next line contains the string $$$t$$$ of the length $$$n$$$, containing lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, output a single line containing the lexicographically smallest string $$$s$$$ which could be a prototype of $$$t$$$.

5

1

a

2

ba

10

codeforces

26

abcdefghijklmnopqrstuvwxyz

26

abcdefghijklmnopqrstuvwxzy

b
ac
abcdebfadg
bcdefghijklmnopqrstuvwxyza
bcdefghijklmnopqrstuvwxyaz

NoteIn the first test case, we couldn't have the string "a", since the letter a would transit to itself. Lexicographically the second string "b" is suitable as an answer.In the second test case, the string "aa" is not suitable, since a would transit to itself. "ab" is not suitable, since the circle would be closed with $$$2$$$ letters, but it must contain all $$$26$$$. The next string "ac" is suitable.Below you can see the schemes for the first three test cases. The non-involved letters are skipped, they can be arbitrary placed in the gaps.

main = -> {
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    t = gets.to_i
    t.times do
        n = gets.to_i
        s = gets.chomp.each_char.map { |c| c.ord - ?a.ord }

        previous = [nil] * 26
        used_to = [false] * 26
        count = 0
        t = ""
        s.each do |c|
            unless previous[c]
                to = (0 ... 26).find { |d|
                    next if d == c || used_to[d]
                    ok = true
                    k = d
                    ok = false if k == c while (k = previous[k])
                    ok
                }
                used_to[to] = true
                previous[c] = to
                count += 1
                if count == 25
                    from = (0 ... 26).find { |i| previous[i].nil? }
                    to = used_to.index(false)
                    used_to[to] = true
                    previous[from] = to
                    count += 1
                end
            end
            t << alphabet[previous[c]]
        end
        puts t
    end
}

main.call


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.

n = gets.chomp
l = n.size

( l - 1 ).times do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	if d < n[ l - 1 ].to_i
		s = String.new( n )
		s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
		puts s
		exit
	end
end

( l - 2 ).downto( 0 ) do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
	puts s
	exit
end

puts -1

n = gets.strip
if n.chars.all? {|x| x.to_i.odd?}
	puts -1
else
	m = n.chars.select{|x| x.to_i.even?}
	i = m.min > n[-1] ? n.rindex(m[-1]) : n.index(m.find{|x| x < n[-1]})
	n[i], n[-1] = n[-1] , n[i]
	puts n
end

a=gets.chomp.split('').map(&:to_i)
n=a.length
i,max,x=0,-1,-1
while i<n
	if a[i]&1==0
		max,x=a[i],i
		break if max<a[n-1]
	end
	i+=1
end
if max==-1
	puts "-1"
else
	i=a[x]
	a[x]=a[n-1]
	a[n-1]=i
	puts a.join
end

a=gets.chomp
t=-1
mi=-10
(a.length-2).downto(0) do |i|
if a[i].to_i%2==0
if t==-1
t=i
next
end
if a[i]<a[a.length-1]
t=i
end
end

end

if t==-1
puts "-1"
else
mi=a[a.length-1]
a[a.length-1]=a[t]
a[t]=mi
puts a
end

n=gets.chomp
m=n.size-1

ans=""

last1=n[m].to_i
p1=-1
m.times{|i|
	e=n[i].to_i
	if e%2==0 && e<last1 then
		p1=i
		break
	end
}
if p1!=-1 then
	n[p1],n[m]=n[m],n[p1]
	ans=(n+"")
	n[p1],n[m]=n[m],n[p1]
end

i=m-1
p1=-1
while i>=0
	e=n[i].to_i
	if e%2==0 && e>last1 then
		p1=i
		break
	end
	i-=1
end

if p1!=-1 then
	n[p1],n[m]=n[m],n[p1]
	ans=n if ans<n
end
if ans=="" then
	puts -1
else
	puts ans
end

def check(s)
	unless s=~/[02468]/
		puts "-1"
		return
	end
	i=0
	flag=false
	hold=s[-1].to_i
	max=-1
	found=false
	while true && i<=8
		if i<hold
			m=s=~/#{i}/
		else
			m=s.reverse=~/#{i}/
			flag=true
		end
		if $~
			if flag
				if found
					break
				end
				m=s.size-m-1
				if m>max
					max=m
				end
			else
				found=true
				if max==-1 || max>m
					max=m
				end
			end
		end
		$~=nil
		i+=2
	end
	#puts max
	puts s[0...max]+s[-1]+s[max+1...-1]+s[max]
end
s=gets.chomp.to_s
check(s)

# coding: utf-8

# 한 자리의 숫자(반드시 짝수) 와 마지막 자리(반드시 홀수)를 교체했을 때
# 가장 큰 숫자를 만들어라
# 단 짝수가 없어서 짝수를 못만들면 -1

# Time limit: 0.5sec

# ex) 2431 라면
# 1432 vs 2134 이면 당연히 후자가 더 크겠지
# ex) 2439 라면
# 9432 vs 2934 이면 당연히 전자가 더 크지
# 즉 교환하려는 홀수가 타겟보다 크다면 최대한 앞자리에 있는게 유리하고(숫자가 커짐)
# 교환하려는 홀수가 타겟보다 작다면 최대한 뒷자리에서 바꾸는게 유리하다
even_indexes = []
ar = []
gets.chomp.split(//).each_with_index { |i, index|
    i = i.to_i
    if i.even?
        even_indexes << index
    end
    ar << i
}

if even_indexes.empty?
    puts "-1"
else
    exchanged = false
    for i in even_indexes
        if ar[i] < ar[-1]
            ar[i], ar[-1] = ar[-1], ar[i]
            exchanged = true
            break
        end
    end

    if !exchanged
        last_even_index = even_indexes.last
        ar[last_even_index], ar[-1] = ar[-1], ar[last_even_index]
    end

    puts ar.join('')
end

copy = gets.chomp
ans = -1
last = copy[-1].to_i

# if copy.length < 20
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
# even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
end
if ans != -1
	copy[ans],copy[-1] = copy[-1],copy[ans]
	ans = copy
end
puts ans
# else
# 	copy.each_char.with_index do |e,i|
# 	v = e.to_i
# 	next if v.to_i.odd?

# 	if v < last
# 		ans = i
# 		break
# 	else
# 		ans = i
# 	end
# 	end
# 	#
# 	puts copy[-1]
# end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = if m.all?{|x| x > n[-1]}
        n.rindex(m[-1])
      else
        n.index(m.find{|x| x < n[-1]})
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.chars.all?{|x| x.to_i.odd?}
  puts -1
else
  m = n.chars.select{|x| x.to_i.even?}
  i = if m.min > n[-1]
        n.rindex(m[-1])
      else
        n.index(m.find{|x| x < n[-1]})
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

a=Array.new
str=gets.to_s
a=str.split("")
h=-1
for i in 0..a.length-2
#  puts a.length
  if a[i].to_i%2==0
    h=i
  end
  if a[i].to_i%2==0 and a[i].to_i<a[-2].to_i
#   a[-1] 字符串最后一般是换行符，可用chomp方法去除
#    puts a[-2]
    t=a[-2]
    a[-2]=a[i]
    a[i]=t
    h=-2
    break
  end
end
if h==-2
  for i in 0..a.length-1
    print a[i].chomp
  end
  puts
elsif h==-1
  puts -1
else
  t=a[-2]
  a[-2]=a[h]
  a[h]=t
   for i in 0..a.length-1
    print a[i].chomp
   end
   puts
end

n = gets
l = n.size

p l

( l - 1 ).times do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	if d < n[ l - 1 ].to_i
		s = String.new( n )
		s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
		puts s
		exit
	end
end

( l - 2 ).downto( 0 ) do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
	puts s
	exit
end

puts -1

n = gets
l = n.size

( l - 1 ).times do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	if d < n[ l - 1 ].to_i
		s = String.new( n )
		s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
		puts s
		exit
	end
end

( l - 2 ).downto( 0 ) do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
	puts s
	exit
end

puts -1

n = gets
l = n.size

l.times do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	if d < n[ l - 1 ].to_i
		s = String.new( n )
		s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
		puts s
		exit 0
	end
end

( l - 2 ).downto( 0 ) do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
	puts s
	exit 0
end

puts -1

n = gets
l = n.size

l.times do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	if d < n[ l - 1 ].to_i
		s = String.new( n )
		s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
		print s
		exit 0
	end
end

( l - 2 ).downto( 0 ) do | i |
	d = n[i].to_i
	if d.odd?
		next
	end

	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]
	print s
	exit 0
end

print -1

n = gets
l = n.size

res = -1

l.times do | i |
	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]

	if s.to_i.even?
		res = [ res, s.to_i ].max
	end
end

puts res

n = gets
l = n.size

res = -1
l.times do | i |
	s = String.new( n )
	s[i], s[ l - 1 ] = s[ l - 1 ], s[i]

	m = s.to_i
	if m.even?
		res = [ res, m ].max
	end
end
puts res

n = gets.strip
numbers = n.split("").map {|i| i.to_i}
even = numbers.select {|n| n.even?}
max = 0
last_index = numbers.size - 1
even.each do |number|
	even_index = numbers.index(number)
	temp = numbers[even_index]
	numbers[even_index] = numbers[last_index]
	numbers[last_index] = temp
	current = numbers.join("").to_i
	if (current > max)
		max = current
	end
	temp = numbers[even_index]
	numbers[even_index] = temp
	numbers[last_index] = temp
end
if even.size == 0
	puts -1
else
	puts max
end

n = gets.strip
numbers = n.split("").map {|i| i.to_i}
numbers2 = numbers.map do |e| e end
even = numbers.select {|n| n.even?}
max = 0
i = -1
j = -1
last_index = numbers.size - 1

numbers.each_with_index do |number, index|
	if (number.even? && number < numbers[last_index])
		i = index
		break
	end
end

numbers.reverse.each_with_index do |number, index|
	if (number.even? && number >= numbers[last_index])
		j = numbers.size - index - 1
		break
	end
end
puts j
if even.size == 0
	puts -1
elsif (i != -1)
	temp = numbers[last_index]
	numbers[last_index] = numbers[i]
	numbers[i] = temp
	puts numbers.join("").to_i
elsif (j != -1)
	temp = numbers[last_index]
	numbers[last_index] = numbers[j]
	numbers[j] = temp
	puts numbers.join("").to_i
end

a=gets.chomp
t=-1
mi=-10
(a.length-2).downto(0) do |i|
if a[i].to_i%2==0 && a[a.length-1].to_i-a[i].to_i>=mi
t=i
mi=a[a.length-1].to_i-a[i].to_i
end
end

if t==-1
puts "-1"
else
mi=a[a.length-1]
a[a.length-1]=a[t]
a[t]=mi
puts a
end

a=gets.chomp
t=-1
mi=-10
(a.length-2).downto(0) do |i|
if a[i].to_i%2==0 && a[a.length-1].to_i-a[i].to_i>mi
t=i
mi=a[a.length-1].to_i-a[i].to_i
end
end

if t==-1
puts "-1"
else
mi=a[a.length-1]
a[a.length-1]=a[t]
a[t]=mi
puts a
end

def check(s)
	unless s=~/[02468]/
		return "-1"
	end
	i=0
	flag=false
	hold=s[-1].to_i
	while true && i<=8
		if i<hold
			m=s=~/#{i}/
		else
			m=s.reverse=~/#{i}/
			flag=true
		end
		if $~
			if flag
				y=s[m]+s[1...m]+s[0]+s[m+1..-1]
				return y.reverse
			else
				y=s[0...m]+s[-1]+s[m+1...-1]+s[m]
				return y
			end
		end
		$~=nil
		i+=2
	end
end
s=gets.chomp.to_s
hold=check(s)
if hold!='-1'
	puts hold
else
	puts "-1"
end

def check(s)
	unless s=~/[02468]/
		puts "-1"
	end
	i=0
	flag=false
	hold=s[-1].to_i
	max=-1
	found=false
	while true && i<=8
		if i<hold
			m=s=~/#{i}/
		else
			m=s.reverse=~/#{i}/
			flag=true
		end
		if $~
			if flag
				if found
					break
				end
				m=s.size-m+1
				if m>max
					max=m
				end
			else
				found=true
				if max==-1 || max>m
					max=m
				end
			end
		end
		$~=nil
		i+=2
	end
	puts s[0...max]+s[-1]+s[max+1...-1]+s[max]
end
s=gets.chomp.to_s
check(s)

def check(s)
	unless s=~/[02468]/
		return "-1"
	end
	i=0
	flag=false
	hold=s[-1].to_i
	while true && i<=8
		if i<hold
			m=s=~/#{i}/
		else
			m=s.reverse=~/#{i}/
			flag=true
		end
		if $~
			if flag
				s=s.reverse
				y=s[m]+s[1...m]+s[0]+s[m+1..-1]
				return y.reverse
			else
				y=s[0...m]+s[-1]+s[m+1...-1]+s[m]
				return y
			end
		end
		$~=nil
		i+=2
	end
end
s=gets.chomp.to_s
hold=check(s)
if hold!='-1'
	puts hold
else
	puts "-1"
end

def check(s)
	unless s=~/[02468]/
		puts "-1"
	end
	i=0
	flag=false
	hold=s[-1].to_i
	max=-1
	found=false
	while true && i<=8
		if i<hold
			m=s=~/#{i}/
		else
			m=s.reverse=~/#{i}/
			flag=true
		end
		if $~
			if flag
				if found
					break
				end
				m=s.size-m-1
				if m>max
					max=m
				end
			else
				found=true
				if max==-1 || max>m
					max=m
				end
			end
		end
		$~=nil
		i+=2
	end
	#puts max
	puts s[0...max]+s[-1]+s[max+1...-1]+s[max]
end
s=gets.chomp.to_s
check(s)

def check(s)
	unless s=~/[02468]/
		return "-1"
	end
	i=0
	s=s.reverse
	while true && i<=8
		m=s=~/#{i}/
		if $~
			y=s[m]+s[1...m]+s[0]+s[m+1..-1]
			return y.reverse
		end
		$~=nil
		i+=2
	end
end
s=gets.chomp.to_s
hold=check(s)
if hold!='-1'
	puts hold
else
	puts "-1"
end

copy = gets.chomp
ans = -1
last = copy[-1].to_i
if copy.length < 20
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
# even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
end
if ans != -1
	copy[ans],copy[-1] = copy[-1],copy[ans]
	ans = copy.to_i
end
puts ans
else
	puts copy[-1]
end

copy = gets.chomp
ans = -1
last = copy[-1].to_i
if copy.length < 20
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
# even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
end
if ans != -1
	copy[ans],copy[-1] = copy[-1],copy[ans]
	ans = copy.to_i
end
puts ans
else
	copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
	end
	puts copy[-1]
end

copy = gets.chomp
ans = -1
last = copy[-1].to_i
if copy.length < 20
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
# even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
end
if ans != -1
	copy[ans],copy[-1] = copy[-1],copy[ans]
	ans = copy.to_i
end
puts ans
else
	copy.each_char.with_index
	puts copy[-1]
end

n = gets.to_i
ans = -1
copy = n.to_s
last = copy[-1].to_i
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
even_nos.each do |e|
	if e[0] < last
		copy[e[1]],copy[-1] = copy[-1],copy[e[1]]
		ans = copy.to_i
		break
	end
end

even_nos.reverse_each do |e|
	if e[0] > last
		copy[e[1]],copy[-1] = copy[-1],copy[e[1]]
		ans = copy.to_i
		break
	end
end

puts ans

copy = gets.chomp
ans = -1
last = copy[-1].to_i
if copy.length < 20
# (0..(copy.length - 1)) do |i|
# 	v = copy[i].to_i
# 	if v.even? && v < last
# 		copy[i],copy[-1] = copy[-1],copy[i]
# 		ans = copy.to_i
# 		break
# 	end
# end
# if ans == -1
# 	((copy.length - 1).downto(0)).each do |i|
# 		v = copy[i].to_i
# 		if v.even? && v > last
# 			copy[i],copy[-1] = copy[-1],copy[i]
# 			ans = copy.to_i
# 			break
# 		end
# 	end
# end
# even_nos = copy.each_char.with_index.map{|k,i| [k.to_i,i] if k.to_i.even?}.compact
copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
end
if ans != -1
	copy[ans],copy[-1] = copy[-1],copy[ans]
	ans = copy.to_i
end
puts ans
else
	copy.each_char.with_index do |e,i|
	v = e.to_i
	next if v.to_i.odd?

	if v < last
		ans = i
		break
	else
		ans = i
	end
	end
	#
	puts copy[-1]
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  i = n.index(n.each_char.find{|x| x.to_i.even?})
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = if m[0] < n[-1]
        n.index(m[0])
      else
        n.rindex(m.min)
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = if m.min > n[-1]
        n.rindex(m.min)
      else
        n.index(m.min)
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = n.rindex(m.min)
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = if m.all?{|x| x < n[-1]}
        n.index(m.find{|x| x < n[-1]})
      else
        n.index(m.min)
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

n = gets.chomp
if n.each_char.all?{|x| x.to_i.odd?}
  puts -1
else
  m = []
  n.each_char{|x| m << x if x.to_i.even?}
  i = if m.all?{|x| x < n[-1]}
        n.index(m.find{|x| x < n[-1]})
      else
        n.rindex(m.min)
      end
  n[i], n[-1] = n[-1], n[i]
  puts n
end

a=Array.new
str=gets.to_s
a=str.split("")
h=0
for i in 0..a.length-1
  if a[i].to_i>0 and a[i].to_i%2==0
#   a[-1] 字符串最后一般是换行符，可用chomp方法去除
#    puts a[-2]
    t=a[-2]
    a[-2]=a[i]
    a[i]=t
    h=1
    break
  end
end
if h==1
  for i in 0..a.length-1
    print a[i].chomp
  end
  puts
elsif h==0
  puts -1
end


You are given two strings $$$s$$$ and $$$t$$$, both of length $$$n$$$. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions:   choose an occurrence of "ab" in $$$s$$$ and replace it with "ba";  choose an occurrence of "bc" in $$$s$$$ and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $$$s$$$ to make it equal to string $$$t$$$?

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line contains string $$$s$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The third line contains string $$$t$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase, print "YES" if you can change string $$$s$$$ to make it equal to string $$$t$$$ by performing an arbitrary amount of moves (possibly, zero). Otherwise, print "NO".

5

3

cab

cab

1

a

b

6

abbabc

bbaacb

10

bcaabababc

cbbababaac

2

ba

ab

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp.chars.to_a
  t = gets.chomp.chars.to_a
  si, ti = s.zip(0..), t.zip(0..)
  sa = si.filter_map { |c, i| i if c == "a" }
  sc = si.filter_map { |c, i| i if c == "c" }
  ta = ti.filter_map { |c, i| i if c == "a" }
  tc = ti.filter_map { |c, i| i if c == "c" }
  ok = s.select { |c| c != "b" } == t.select { |c| c != "b" } &&
       sa.zip(ta).all? { |x, y| x <= y } &&
       sc.zip(tc).all? { |x, y| x >= y }
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp
  t = gets.chomp

  if s.count('b') != t.count('b')
    puts 'NO'
    next
  end

  j = 0
  ok = true
  n.times do |i|
    next if s[i] == 'b'

    while t[j] == 'b'
      j += 1
    end

    if s[i] != t[j] || (s[i] == 'a' && i > j) || (s[i] == 'c' && i < j)
      ok = false
      break
    end
    j += 1

  end
  puts ok ? 'YES' : 'NO'
end

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp.chars.to_a
  t = gets.chomp.chars.to_a
  si, ti = s.zip(0..), t.zip(0..)
  sa = si.filter_map { |c, i| i if c == "a" }
  sc = si.filter_map { |c, i| i if c == "c" }
  ta = ti.filter_map { |c, i| i if c == "a" }
  tc = ti.filter_map { |c, i| i if c == "c" }
  ok = s.select { |c| c != "b" } == t.select { |c| c != "b" } && (sa <=> ta) <= 0 && (sc <=> tc) >= 0
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp.chars.to_a
  t = gets.chomp.chars.to_a
  si, ti = s.zip(0..), t.zip(0..)
  sa = si.filter_map { |c, i| i if c == "a" }
  sb = si.filter_map { |c, i| i if c == "b" }
  sc = si.filter_map { |c, i| i if c == "c" }
  ta = ti.filter_map { |c, i| i if c == "a" }
  tb = ti.filter_map { |c, i| i if c == "b" }
  tc = ti.filter_map { |c, i| i if c == "c" }
  ok = sa.count == ta.count && sb.count == tb.count && sc.count == tc.count && (sa <=> ta) <= 0 && (sc <=> tc) >= 0
  puts ok ? "YES" : "NO"
end


The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 ≤ ai ≤ 32768); number ai denotes the maximum data transfer speed on the i-th computer.

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.

# https://codeforces.com/problemset/problem/412/B

input = gets.split(' ').map(&:to_i)
transfer_speed_table = gets.split(' ').map(&:to_i)

k = input[1]

transfer_speed_table.sort! { |a, b| b <=> a }

puts transfer_speed_table[k-1]

nk = gets.split(' ')
n = nk[0].to_i
k = nk[1].to_i
ai = gets.split(' ').map!{ |el| el.to_i }
ai = ai.sort.reverse
puts ai[k-1]

#!/usr/bin/env ruby

class Main
  attr_reader :computer_count, :student_count, :array

  def initialize(computer_count, student_count, array)
    @computer_count = computer_count
    @student_count = student_count
    @array = array.sort.reverse
  end

  def run
    array[student_count - 1]
  end
end

computer_count, student_count = gets.split(" ")
array = gets.split(" ")
puts Main.new(computer_count.to_i, student_count.to_i, array.map(&:to_i)).run

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

a =  gets.split(' ').map(&:to_i).sort.reverse

puts a[k-1]

n, m = gets.split
a = gets.split.map{|i|i.to_i}.sort
print a[-m.to_i]


You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive.  All the written labels are distinct.  The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.

Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).

n = gets.to_i
ab = n.pred.times.map {gets.split.map(&:to_i).map(&:pred)}
cnt = Array.new(n, 0)
ab.each{|a| a.each{|i| cnt[i] += 1}}
ans = Array.new(n.pred, -1)
if (pos = cnt.index{|c| c >= 3})
	(0...n.pred).to_a.select{|i| ab[i].index(pos)}.take(3).each_with_index{|i, x| ans[i] = x}
	(0...n.pred).to_a.select{|i| ans[i] == -1}.each_with_index{|i, x| ans[i] = x + 3}
else
	ans = (0...n.pred).to_a
end
puts ans.join("\n")

n = gets.to_i
ab = n.pred.times.map {gets.split.map(&:to_i).map(&:pred)}
cnt = Array.new(n, 0)
ab.each do |a, b|
	cnt[a] += 1
	cnt[b] += 1
end

pos = cnt.index {|c| c >= 3}
ans = Array.new(n.pred, -1)
if pos
	x = 0
	n.pred.times do |i|
		if ab[i].index(pos) && x < 3
			ans[i] = x
			x += 1
		end
	end
	n.pred.times do |i|
		if ans[i] == -1
			ans[i] = x;
			x += 1
		end
	end
else
	ans = (0...n.pred).to_a
end
puts ans.join("\n")


Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $$$n$$$ players arranged in a circle, so that for all $$$j$$$ such that $$$2 \leq j \leq n$$$, player $$$j - 1$$$ is to the left of the player $$$j$$$, and player $$$j$$$ is to the right of player $$$j - 1$$$. Additionally, player $$$n$$$ is to the left of player $$$1$$$, and player $$$1$$$ is to the right of player $$$n$$$.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $$$0$$$, $$$1$$$, or $$$2$$$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $$$1$$$ other player, then they should logically attack that player in response. If instead a player is being attacked by $$$0$$$ or $$$2$$$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $$$n$$$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The descriptions of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$)  — the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. The $$$j$$$-th character of $$$s$$$ is equal to L if the $$$j$$$-th player is attacking the player to their left, and R if the $$$j$$$-th player is attacking the player to their right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints.

5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR

NoteIn the first test case, players $$$1$$$ and $$$2$$$ are attacking each other, and players $$$3$$$ and $$$4$$$ are attacking each other. Each player is being attacked by exactly $$$1$$$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $$$0$$$.In the second test case, not every player acts logically: for example, player $$$3$$$ is attacked only by player $$$2$$$, but doesn't attack him in response. Omkar can talk to player $$$3$$$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $$$1$$$.

# require 'pry'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split('')

  same = true
  (1...n).each do |i|
    if arr[i] != arr[i-1]
      same = false
      break
    end
  end
  if same
    puts((n + 2) / 3)
  else
    last_index = 0
    cnt = 1
    list = []
    (1...n).each do |i|
      if arr[i] == arr[last_index]
        cnt += 1
      else
        list << cnt
        last_index = i
        cnt = 1
      end
    end
    if arr[0] == arr[n - 1]
      list[0] = list[0].to_i + cnt
    else
      list << cnt
    end
    puts list.inject(0) { |sum, ele| sum + ele / 3 }
  end
end

# require 'pry'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split('')
  ans = 0
  (0...n).each do |i|
    attacked_by_count = 0
    attacked_by_count += 1 if arr[(i - 1) % n] == 'R'
    attacked_by_count += 1 if arr[(i + 1) % n] == 'L'
    next if [0, 2].include?(attacked_by_count)

    if arr[i] == 'R' && arr[(i - 1) % n] == 'R'
      arr[i] = 'L'
      ans += 1
    end
    if arr[i] == 'L' && arr[(i + 1) % n] == 'L'
      arr[i] = 'R'
      ans += 1
    end
  end
  puts ans
end

# require 'pry'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split('')
  last_index = 0
  cnt = 1
  list = []
  (1...n).each do |i|
    if arr[i] == arr[last_index]
      cnt += 1
    else
      list << cnt
      last_index = i
      cnt = 1
    end
  end
  if arr[0] == arr[n - 1]
    list[0] = list[0].to_i + cnt
  else
    list << cnt
  end
  puts list.inject(0) { |sum, ele| sum + ele / 3 }
end


You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that:  No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$);  the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.

For each query, print the answer on it — the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)

NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students.

n = readline.to_i
n.times do |i|
  m = readline.to_i
  a = readline.to_s.split
  ni = []
  a.each {|ite|
    ni.push(ite.to_i)
  }
  ni = ni.sort
  last = ni[0]
  ch = 0
  ni.each { |ite |
    if (ite - last).abs == 1
      ch = 1
      break
    end
    last = ite
  }
  if ch == 1
    puts 2
  else
    puts 1
  end
end

gets.to_i.times{
    n=gets.to_i
    a=gets.split.map(&:to_i).sort
    p (0...n-1).count{|i|a[i]+1==a[i+1]}>0 ? 2 : 1
}

gets.to_i.times do
  n = gets.to_i
  as = gets.split.map(&:to_i).sort
  flg = false
  (0..n-2).each do |i|
    flg = true if (as[i] - as[i+1]).abs == 1
  end
  puts flg ? 2 : 1
end

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

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 kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

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

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

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

def bit(n) n.to_s(2).split("").map(&:to_i) end

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

n = inp[0]
n.times do
  q = inp[0]
  st = inp
  mae = -9
  ans = 1
  st.sort!
  st.each do |d|
    if(d - mae == 1)
      ans = 2
      break
    end
    mae = d
  end
  puts ans

end

q = gets.to_i
q.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).sort
  nteams, nused, used = 0, 0, []
  while nused < n
    i = 0
    t = nil
    while i < n
      if not used[i] and (not t or (a[i] - t).abs > 1)
        t = a[i]
        nused += 1
        used[i] = true
      end
      i += 1
    end
    nteams += 1
  end
  puts nteams
end

q = gets.to_i
q.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  nteams, nused, used = 0, 0, []
  while nused < n
    i = 0
    t = nil
    while i < n
      if not used[i] and (not t or (a[i] - t).abs > 1)
        t = t || a[i]
        nused += 1
        used[i] = true
      end
      i += 1
    end
    nteams += 1
  end
  puts nteams
end


Polycarp has invited $$$n$$$ friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.Each friend is characterized by two values $$$h_i$$$ (their height) and $$$w_i$$$ (their width). On the photo the $$$i$$$-th friend will occupy a rectangle $$$h_i \times w_i$$$ (if they are standing) or $$$w_i \times h_i$$$ (if they are lying on the side).The $$$j$$$-th friend can be placed in front of the $$$i$$$-th friend on the photo if his rectangle is lower and narrower than the rectangle of the $$$i$$$-th friend. Formally, at least one of the following conditions must be fulfilled:  $$$h_j < h_i$$$ and $$$w_j < w_i$$$ (both friends are standing or both are lying);  $$$w_j < h_i$$$ and $$$h_j < w_i$$$ (one of the friends is standing and the other is lying). For example, if $$$n = 3$$$, $$$h=[3,5,3]$$$ and $$$w=[4,4,3]$$$, then:  the first friend can be placed in front of the second: $$$w_1 < h_2$$$ and $$$h_1 < w_2$$$ (one of the them is standing and the other one is lying);  the third friend can be placed in front of the second: $$$h_3 < h_2$$$ and $$$w_3 < w_2$$$ (both friends are standing or both are lying). In other cases, the person in the foreground will overlap the person in the background.Help Polycarp for each $$$i$$$ find any $$$j$$$, such that the $$$j$$$-th friend can be located in front of the $$$i$$$-th friend (i.e. at least one of the conditions above is fulfilled).Please note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend $$$i$$$ any other friend $$$j$$$ who can be located in front of him. Think about it as you need to solve $$$n$$$ separate independent subproblems.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of friends. This is followed by $$$n$$$ lines, each of which contains a description of the corresponding friend. Each friend is described by two integers $$$h_i$$$ and $$$w_i$$$ ($$$1 \leq h_i, w_i \leq 10^9$$$) — height and width of the $$$i$$$-th friend, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output $$$n$$$ integers on a separate line, where the $$$i$$$-th number is the index of a friend that can be placed in front of the $$$i$$$-th. If there is no such friend, then output -1. If there are several answers, output any.

NoteThe first test case is described in the statement.In the third test case, the following answers are also correct:   $$$[-1, -1, 1, 2]$$$;  $$$[-1, -1, 1, 1]$$$;  $$$[-1, -1, 2, 1]$$$.

gets.to_i.times do
  n = gets.to_i
  a = []
  n.times do |i|
    h, w = gets.split.map &:to_i
    h, w = w, h if h < w
    a << [i, h, w]
  end
  a.sort_by! { |it| [it[1], -it[2]] }
  mn, pos = 1E18.to_i, -1
  res = [-1] * n
  a.each_with_index do |it|
    i, _, w = it
    res[i] = pos + 1 if w > mn
    if w < mn
      mn, pos = w, i
    end
  end
  puts res.join' '
end

gets.to_i.times do
  n = gets.to_i
  a = []
  n.times do |i|
    h, w = gets.split.map &:to_i
    h, w = w, h if h < w
    a << [i, h, w]
  end
  a.sort_by! { |it| [it[1], -it[2]] }
  mn, pos = 1E18.to_i, -1
  a.each_with_index do |it, i|
    print pos + 1, ' ' if it[1] > mn
    if it[1] < mn
      mn, pos = it[1], i
    end
  end
  puts
end

INF = 1E10.to_i
def solve(a, h, w, i)
  pref = []
  cur = [[INF, -1], [INF, -1]]
  a.each do |it|
    if it[1] < cur[0][0]
      cur[0], cur[1] = [it[1], it[2]], cur[0]
    else
      cur[1] = [cur[1], [it[1], it[2]]].min
    end
    pref << [it[0], cur]
  end
  l, r = -1, a.size
  while r - l > 1
    m = (l + r) / 2
    if pref[m][0] < h
      l = m
    else
      r = m
    end
  end
  return -1 if l == -1
  m1, m2 = pref[l][1][0], pref[l][1][1]
  if m1[1] != i
     m1[0] < w ? m1[1] + 1 : -1
  else
     m2[0] < w ? m2[1] + 1 : -1
  end
end
gets.to_i.times do
  n = gets.to_i
  h, w, a, b = [0] * n, [0] * n, [], []
  n.times do |i|
    h[i], w[i] = gets.split.map &:to_i
    a << [h[i], w[i], i]
    b << [w[i], h[i], i]
  end
  a.sort!
  b.sort!
  n.times do |i|
    res = solve(a, h[i], w[i], i)
    solve(b, h[i], w[i], i) if res == -1
    print res, ' '
  end
  puts
end

INF = 1E10.to_i
def solve(a, w, h, i)
  pref = []
  cur = [[INF, -1], [INF, -1]]
  a.each do |it|
    if it[1] < cur[0][0]
      cur[0], cur[1] = [it[1], it[2]], cur[0]
    else
      cur[1] = [cur[1], [it[1], it[2]]].min
    end
    pref << [it[0], cur]
  end
  l, r = -1, a.size
  while r - l > 1
    m = (l + r) / 2
    if pref[m][0] < h
      l = m
    else
      r = m
    end
  end
  return -1 if l == -1
  m1, m2 = pref[l][1][0], pref[l][1][1]
  if m1[1] != i
     m1[0] < w ? m1[1] + 1 : -1
  else
     m2[0] < w ? m2[1] + 1 : -1
  end
end
gets.to_i.times do
  n = gets.to_i
  h, w, a, b = [0] * n, [0] * n, [], []
  n.times do |i|
    h[i], w[i] = gets.split.map &:to_i
    a << [h[i], w[i], i]
    b << [w[i], h[i], i]
  end
  a.sort!
  b.sort!
  n.times do |i|
    res = solve(a, h[i], w[i], i)
    solve(b, h[i], w[i], i) if res == -1
    print res, ' '
  end
  puts
end


A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.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 first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$).

For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  a = ""
  b = ""
  diff = false
  x = gets.chomp
  for i in 0..n-1
    if x[i] == "2"
      if diff
        a << "0"
        b << "2"
      else
        a << "1"
        b << "1"
      end
    elsif x[i] == "1"
      if diff
        a << "0"
        b << "1"
      else
        a << "1"
        b << "0"
        diff = true
      end
    else
      a << "0"
      b << "0"
    end
  end
  puts a
  puts b
end

gets.to_i.times do
	n = gets.to_i
	s = gets.split('').map(&:to_i)
	a = Array.new(0, n)
	b = Array.new(0, n)

	flag = false
	n.times do |i|
		if flag
			a[i] = 0
			b[i] = s[i]
		else
			a[i] = (s[i] + 1) / 2
			b[i] = s[i] / 2
			flag = true if a[i] != b[i]
		end
	end
	puts a.join('')
	puts b.join('')
end

# coding: utf-8

# if __FILE__ == $0
# end

t = gets.to_i
t.times {
    len = gets.to_i
    tnr = gets.chomp
    a = []
    b = []
    a_equals_b = true
    for i in 0...len
        case tnr[i]
        when '2' # how to split 2? (2, 0), (1, 1), (0, 2)
            if a_equals_b == true
                a << 1
                b << 1
            else
                a << 0
                b << 2
            end
        when '1' # where to increase one?
            if a_equals_b == true
                a << 1
                b << 0
                a_equals_b = false
            else
                a << 0
                b << 1
            end
        when '0' # nothing to do
            a << 0
            b << 0
        else
            raise Exception.new("should not reach here")
        end
    end

    puts a.join('')
    puts b.join('')
}

t = gets.to_i
t.times do
  n = gets.to_i
  x = gets.chomp
  a = []
  b = []
  diff = false
  x.each_char do |c|
    case c
    when "0"
      a.push("0")
      b.push("0")
    when "1"
      if diff
        a.push("0")
        b.push("1")
      else
        a.push("1")
        b.push("0")
        diff = true
      end
    when "2"
      if diff
        a.push("0")
        b.push("2")
      else
        a.push("1")
        b.push("1")
      end
    end
  end
  puts a.join
  puts b.join
end

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

  pos = s.index('1')
  beg = s[0, pos ? pos : s.size ].chars.map { |c| c == '2' ? '1' : '0' }.join

  if pos
    puts beg + '1' + '0' * (n - pos - 1)
    puts beg + '0' + s[pos+1, n - pos - 1]
  else
    puts beg
    puts beg
  end

  next

  odd = false
  result = ['', '']
  gets.chomp.chars.each_with_index do |char, idx|
    if odd
      result[1] += char
      next
    end

    case char
    when '2'
      result.map! { |s| s + '1' }
    when '1'
      result[0] += '1' + '0' * (n - idx - 1)
      result[1] += '0'
      odd = true
    when '0'
      result.map! { |s| s + '0' }
    end
  end

  result.each { |s| puts s }
end

t = gets.to_i
(1..t).each do
  n = gets.to_i
  s = gets.split('')
  b = false
  s.each do |c|
    if c=="\n"
      break
    end
    if b
      print '0'
    else
      print c.to_i/2+c.to_i.modulo(2)
    end
    if c=='1'
      b=true
    end
  end
  print "\n"
  b=false
  s.each do |c|
    if c=="\n"
      break
    end
    if b
      print c
    else
      print c.to_i/2
    end
    if c=='1'
      b=true
    end
  end
  print "\n"
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  a = ""
  b = ""

  x = gets.chomp.split('')
  x.each do |i|
    if i == "2"
      a << "1"
      b << "1"
    elsif i == "1"
      a << "1"
      b << "0"
    else
      a << "0"
      b << "0"
    end
  end
  puts a
  puts b
end

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

  odd = false
  result = ['', '']
  gets.chomp.chars.each_with_index do |char, idx|
    if odd
      result[1] += char
      next
    end

    case char
    when '2'
      result.map! { |s| s + '1' }
    when '1'
      result[0] += '1' + '0' * (n - idx)
      result[1] += '0'
      odd = true
    when '0'
      result.map! { |s| s + '0' }
    end
  end

  result.each { |s| puts s }
end


The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.Find the size of the maximum clique in such graph.

The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points. Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.

Print a single number — the number of vertexes in the maximum clique of the given graph.

NoteIf you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!The picture for the sample test.

n = gets.strip.to_i
xws = readlines.map {|line| line.strip.split.map(&:to_i) }

xws = xws.map {|x,w| [x-w, x+w] }.sort_by(&:last)

result=0
target=0
index=target
until index==n
  index=target+1
  ct = xws[target].last
  index+=1 while xws[index] && xws[index].first < ct
  target = index

  result+=1
end

p result

n = gets.to_i
arr = []
n.times do
	x, w = gets.split.map(&:to_i)
	arr << [x - w, x + w]
end

arr.sort! do |a, b|
	a[1] <=> b[1]
end

ans = 0
now = -10**9
arr.each do |ele|
	if ele[0] >= now
		ans += 1
		now = ele[1]
	end
end

puts ans


Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.For example, if X = 10910 = 11011012, Y = 4110 = 1010012, then:  X xor Y  =  6810  =  10001002. Write a program, which takes two non-negative integers A and B as an input and finds two non-negative integers X and Y, which satisfy the following conditions:   A = X + Y  B  =  X xor Y, where xor is bitwise exclusive or.  X is the smallest number among all numbers for which the first two conditions are true.

The first line contains integer number A and the second line contains integer number B (0 ≤ A, B ≤ 264 - 1).

The only output line should contain two integer non-negative numbers X and Y. Print the only number -1 if there is no answer.

#Infinity
#geti,getia
#Object # dcopy
#
#String # to_a
#   "abc".to_a #=> ["a","b","c"]
#String # to_ia
#   "1 2 3".to_ia #=> [1,2,3]
#
#Array # rsort,rsort!
#   [1,3,2,4].rsort #=> [4,3,2,1]
#
#Integer # divisor
#   24.divisor #=> [1,2,3,4,6,8,12,24]
#
include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0
class Matrix;def inspect;empty? ? "Matrix.empty(#{row_size}, #{column_size})":"Matrix[\n#{@rows.map(&:inspect).join("\n")}\n]";end;end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;end
class String;def to_ia;split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end
class Array;def rsort;sort.reverse;end;def rsort!;sort!.reverse!;end;end

def dfs(a,b,x,y,n)
    mask = ((1<<n)-1)
    return false if ((x+y)&mask) != a&mask || (x^y)&mask != b&mask
    return [x,y] if x+y == a && x^y == b
    return false if x+y > a
    for p in 0..1
        for q in 0..1
            s = x | (p * (1<<n))
            t = y | (q * (1<<n))
            w = dfs(a,b,s,t,n+1)
            return w if w != false
        end
    end
    return false
end
a = geti
b = geti
res = dfs(a,b,0,0,0)
if res == false
    puts -1
else
    puts "#{res[0]} #{res[1]}"
end

a = gets.to_i
b = gets.to_i

x = (a - b)/2

if a - b >= 0 and (a - b) % 2 == 0
  puts x.to_s + " " + (x + b).to_s + "\n"
else
  puts "-1\n"
end


There is a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are conveniently labeled from $$$1$$$ to $$$n$$$. The weights are positive integers at most $$$100$$$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes $$$p$$$ and $$$q$$$, and the judge will return the maximum distance between a node in $$$p$$$ and a node in $$$q$$$. In the words, maximum distance between $$$x$$$ and $$$y$$$, where $$$x \in p$$$ and $$$y \in q$$$. After asking not more than $$$9$$$ questions, you must report the maximum distance between any pair of nodes.

NoteIn the first example, the first tree looks as follows: In the first question, we have $$$p = {1}$$$, and $$$q = {2, 3, 4, 5}$$$. The maximum distance between a node in $$$p$$$ and a node in $$$q$$$ is $$$9$$$ (the distance between nodes $$$1$$$ and $$$5$$$).The second tree is a tree with two nodes with an edge with weight $$$99$$$ between them.

def say(s)
  puts s
  STDOUT.flush
end

readline.to_i.times do
  n = readline.to_i
  r = 0
  bit = 1
  while bit < n do
    a, b = (1..n).partition { |i| i & bit > 0 }
    say "#{a.length} #{b.length} #{a.join " "} #{b.join " "}"
    r1 = readline.to_i
    if r1 > r then r = r1 end
    if r1 < 0 then exit end
    bit <<= 1
  end
  say "-1 #{r}"
end

T = gets.to_i
T.times do
  n = gets.to_i
  t = 1
  ans = 0
  9.times do
    l = []
    r = []
    n.times do |i|
      if i & t > 0
        l << i+1
      else
        r << i+1
      end
    end
    if l.length>0 && r.length>0
      puts "#{l.length} #{r.length} #{l.join(" ")} #{r.join(" ")}"
      STDOUT.flush
      x = gets.to_i
      ans = x if x > ans
    end
    t *= 2
  end
  puts "-1 #{ans}"
  STDOUT.flush
end


There are $$$n$$$ kids, numbered from $$$1$$$ to $$$n$$$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (all these numbers are from $$$1$$$ to $$$n$$$ and are distinct, so $$$p$$$ is a permutation). Let the next kid for a kid $$$p_i$$$ be kid $$$p_{i + 1}$$$ if $$$i < n$$$ and $$$p_1$$$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $$$x$$$) and the next kid for $$$x$$$. Each kid told you which kids he/she remembered: the kid $$$i$$$ remembered kids $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$. However, the order of $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ can differ from their order in the circle.    Example: 5 kids in a circle, $$$p=[3, 2, 4, 1, 5]$$$ (or any cyclic shift). The information kids remembered is: $$$a_{1,1}=3$$$, $$$a_{1,2}=5$$$; $$$a_{2,1}=1$$$, $$$a_{2,2}=4$$$; $$$a_{3,1}=2$$$, $$$a_{3,2}=4$$$; $$$a_{4,1}=1$$$, $$$a_{4,2}=5$$$; $$$a_{5,1}=2$$$, $$$a_{5,2}=3$$$. You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of the kids. The next $$$n$$$ lines contain $$$2$$$ integers each. The $$$i$$$-th line contains two integers $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ ($$$1 \le a_{i, 1}, a_{i, 2} \le n, a_{i, 1} \ne a_{i, 2}$$$) — the kids the $$$i$$$-th kid remembered, given in arbitrary order.

Print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — permutation of integers from $$$1$$$ to $$$n$$$, which corresponds to the order of kids in the circle. If there are several answers, you may print any (for example, it doesn't matter which kid is the first in the circle). It is guaranteed that at least one solution exists.

# Utility
class Child
  attr_reader :memorised
  attr_reader :index

  def to_s
    @index.to_s
  end

  def log
    "Index: #{@index}. Memory: #{@memorised}"
  end

  def to_i
    @index
  end

  def remembers?(e)
    @memorised.any? { |o| o == e.to_i }
  end

  def initialize(index, *other)
    @index = index
    case other.length
    when 2
      @memorised = [other[0], other[1]]
    when 1
      @memorised = other[0].split.map { |s| s.to_i }
    end
  end
end

# Input
n = gets.to_i
children = []
n.times { |i| children.push Child.new(i + 1, gets) }

if n == 3
  # Special case
  puts "1 2 3"
  exit 0
end

# Processing
roundelay = Array.new(n)
roundelay[0] = children[0]
1.upto(n - 1) do |i|
  mem = roundelay[i - 1].memorised
  c_1 = children[mem[0] - 1]
  c_2 = children[mem[1] - 1]

  #puts roundelay[i - 1].log
  #puts c_1.log
  #puts c_2.log
  #puts

  roundelay[i] = c_1.remembers?(c_2) ? c_1 : c_2
end

# Output
puts roundelay.join(" ")

n = gets.to_i

hash = Hash.new([])
(1..n).each do |x|
  hash[x] += gets.chomp.split(" ").map(&:to_i)
end

arr = []

thefirstpair = hash[1]
if hash[thefirstpair[0]].include?(thefirstpair[1])
  nextone = thefirstpair[0]
  otherone = thefirstpair[1]
else
  nextone = thefirstpair[1]
  otherone = thefirstpair[0]
end

arr.push 1

while nextone != 1
  arr.push nextone
  asdf = nextone
  nextone = otherone
  otherone = (hash[asdf] - [nextone])[0]
end

arr.each do |x|
  print x
  print " "
end

puts

# Utility
class Child
  attr_reader :memorised
  attr_reader :index

  def to_s
    @index.to_s
  end

  def to_i
    @index
  end

  def remembers?(e)
    @memorised.find_index(e.to_i) != nil
  end

  def initialize(index, *other)
    @index = index
    case other.length
    when 2
      @memorised = [other[0], other[1]]
    when 1
      @memorised = other[0].split.map { |s| s.to_i }
    end
  end
end

# Input
n = gets.to_i
children = []
n.times { |i| children.push Child.new(i + 1, gets) }

# Processing
#p children
roundelay = Array.new(n)
roundelay[0] = children[0]
1.upto(n - 1) do |i|
  mem = roundelay[i - 1].memorised
  #p mem
  roundelay[i] = children[mem[0] - 1].remembers?(mem[1]) ? children[mem[0] - 1] : children[mem[1] - 1]
  #puts roundelay[i]
end

# Output
puts roundelay.join(" ")


After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$1 \le k \le 10^9$$$) — the number of mountains and the number of boulders. The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 100$$$) — the height of the mountains. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case, print $$$-1$$$ if the $$$k$$$-th boulder will fall into the collection system. Otherwise, print the position of the $$$k$$$-th boulder.

NoteLet's simulate the first case:  The first boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,2,2,3]$$$.  The second boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ the boulder rolls to $$$i = 2$$$; since $$$h_2 \ge h_3$$$ the boulder rolls to $$$i = 3$$$ and stops there because $$$h_3 < h_4$$$.  The new heights are $$$[4,2,3,3]$$$.  The third boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,3,3,3]$$$. The positions where each boulder stopped are the following: $$$[2,3,2]$$$.In the second case, all $$$7$$$ boulders will stop right at the first mountain rising its height from $$$1$$$ to $$$8$$$.The third case is similar to the first one but now you'll throw $$$5$$$ boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to $$$[4, 3, 3, 3]$$$, that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.

t = gets.chomp.to_i
t.times do
  n, k = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  arr << 0
  arr << 1000
  pik = 0
  prev_pik = 0
  sum = 0

  while arr[pik] >= arr[pik + 1]
    pik += 1
  end
  # puts "PIK = #{pik}"
  while (pik != n && sum < k)
    prev_pik = pik
    sum += [arr[pik + 1], arr[pik - 1] + 1].min - arr[pik]
    arr[pik] = [arr[pik + 1], arr[pik - 1] + 1].min
    pik = 0
    while arr[pik] >= arr[pik + 1]
      pik += 1
    end

    # puts "Arr = #{arr.to_s}"
  end

  # puts "SUM = #{sum}"
  # puts "PIK = #{pik}"
  # puts "Arr = #{arr.to_s}"
  if sum < k
    puts -1
  else
    puts prev_pik + 1
  end
end

#     int t,n,k;
#     cin>>t;
#     while(t--)
#     {
#         cin>>n>>k;
#         int a[n];
#         for(int i=0;i<n;i++)
#         cin>>a[i];
#         int j=0,c=0;
#         int p[100000]={0};
#         while(true)
#         {int f=0;
#             for(int i=0;i<n-1;i++)
#             {
#                 if(a[i]<a[i+1])
#                 {f=1;
#                     a[i]=a[i]+1;
#                     c++;
#                     p[c]=i+1;

#                     break;
#                 }
#             }
#             if(f==0)
#             break;
#         }
#         if(k>c)
#         cout<<-1<<"\n";
#         else
#         cout<<p[k]<<"\n";
#     }
# }

t = gets.chomp.to_i;
while t>0 do
    b=Array.new(2)
    b=gets.chomp.split().map { |e| e.to_i  }
    n = b[0];
    k =b[1];

    a=Array.new(n+1);
    i=0;
    p=Array.new(100000);
    a=gets.chomp.split().map { |e| e.to_i  }

    c=0
    h=0
    while h==0 do
        f=0
        j=0
        while j<n-1 do
            if a[j]<a[j+1]
                f=1
                a[j]=a[j]+1
                c=c+1
                p[c]=j+1
                break
            end
            j=j+1
        end
        if f==0
           h=1
        end
    end
    if k>c
        puts -1;
    else
        puts p[k];
    end
    t=t-1
end

def read
    gets.split.map &:to_i
end
gets.to_i.times do
    n, k = read
    a = read
    if n * a.max < k
        puts -1
        next
    end
    res = n + 1
    k.times do
        to = -2
        (n - 1).times do |i|
            if a[i] < a[i + 1]
                to = i
                break
            end
        end
        res = to + 1
        break if res == -1
        a[to] += 1
    end
    puts res
end

def solve
  n, k = ints
  h = ints

  ans = -1
  k.times do
    has_valley = false
    (n-1).times do |i|
      if h[i] < h[i+1]
        ans = i + 1
        has_valley = true
        h[i] += 1
        break
      end
    end
    unless has_valley
      ans = -1
      break
    end
  end
  puts ans
end

def main
  t = int
  t.times do
    solve
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

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 rep(n, &b); Array.new(n, &b) end
def yes; puts YESNO[1] end
def no; puts YESNO[0] end
def yesno t; puts YESNO[t] end
def 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 * mod_inv(y, mod) % 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
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
  n,k=gets.split.map(&:to_i)
  h=gets.split.map(&:to_i)
  f=false
  k.times do |kk|
    f=false
    (n-1).times do |i|
      if h[i]<h[i+1]
        h[i]+=1
        f=i
        break
      end
    end
    if !f
      puts "-1"
      break
    end
  end
  if f
    puts f+1
  end
end

t = gets.chomp.to_i
t.times do
  n, k = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  arr << 0
  arr << 1000
  pik = 0
  prev_pik = 0
  sum = 0

  while arr[pik] >= arr[pik + 1]
    pik += 1
  end
  # puts "PIK = #{pik}"
  while (pik != n && sum < k)
    prev_pik = pik
    sum += arr[pik + 1] - arr[pik]
    arr[pik] = arr[pik + 1]
    pik = 0
    while arr[pik] >= arr[pik + 1]
      pik += 1
    end

  end

  # puts "SUM = #{sum}"
  # puts "PIK = #{pik}"
  # puts "Arr = #{arr.to_s}"
  if sum < k
    puts -1
  else
    puts prev_pik + 1
  end
end


The mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.

Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data.  The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.

For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.

NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.

def dp(pos, turn)
	return $dp[3*turn+pos] if $dp[3*turn+pos] != nil
	return $dp[3*turn+pos]=false if $state[pos][3*turn] != "."
	return $dp[3*turn+pos]=false if $state[pos][3*turn+1] != "."
	return $dp[3*turn+pos]=false if $state[pos][3*turn-1] != "."
	return $dp[3*turn+pos]=false if $state[pos][3*turn-2] != "."
	return $dp[3*turn+pos]=true if 3*turn >= $cols

	if pos == 0
		return $dp[3*turn+pos] = dp(0, turn+1) || dp(1, turn+1)
	end

	if pos == 1
		return $dp[3*turn+pos] = dp(0, turn+1) || dp(1, turn+1) || dp(2, turn+1)
	end

	if pos == 2
		return $dp[3*turn+pos] = dp(1, turn+1) || dp(2, turn+1)
	end
end

gets.to_i.times do
	$cols, $k = *gets.split(" ").map(&:to_i)

	$state = [
		gets.strip+"."*500,
		gets.strip+"."*500,
		gets.strip+"."*500
	]

	$dp = [nil]*$cols

	init = $state[0][0] == "s" ? 0 : $state[1][0] == "s" ? 1 : 2
	$state[init][0] = "."

	puts dp(init, 0) ? "YES" : "NO"
	#p $dp

end


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

#!/usr/bin/ruby
N,H,K=gets.split.map(&:to_i)
r=h=0
gets.split.map(&:to_i).each{|x|
	if h+x<=H
		h+=x
	else
		r+=1
		h=x
	end
	r+=h/K
	h%=K
}
p r+(h+K-1)/K

n, h, k = readline.split(' ').collect(&:to_i)
arr = readline.split(' ').collect(&:to_i)
left = 0
ct = 0
arr.each do |num|
  if left + num > h
    left = num
    ct += 1
  else
    left += num
  end
  ct += (left / k)
  left %= k
end

ct += 1 if left > 0
puts ct

n, h, k = gets.split.map { |x| x.to_i }
a = gets.split.map { |x| x.to_i }
ans = 0
sum = 0
a.each do |now|
	cut = [(now - (h - sum) + k - 1) / k, 0].max
	ans += cut
	sum = [sum - cut * k, 0].max
	sum += now
end
ans += (sum + k - 1) / k
puts ans

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

t = 0
l = 0

for i in 0...n
  t += l / k
  l = l % k
  if h < l + as[i]
    t += 1
    l = 0
  end
  l += as[i]
end
t += (l + k - 1) / k

puts t

n, h, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
left = 0
i = 0
while i < n
  ans += (left + a[i]) / k
  left = (left + a[i]) % k
  if i == n - 1 && left > 0
    ans += 1
  elsif i != n - 1 && left != 0 && left + a[i + 1] > h
    ans += 1
    left = 0
  end
  i += 1
end
puts ans

n,h,k=gets.split.map(&:to_i)
s=r=0
gets.split.each{|p|p=p.to_i
r+=p
r,s=p,s+1if r>h
s+=r/k
r%=k}
s+=1if r>0
p s

totalPotatos, processorHeight, smashUnits = gets.split.map(&:to_i)
seconds = 0
remain = 0
gets.split.map(&:to_i).each { |potato|
  if remain + potato <= processorHeight
    remain += potato
  else
    seconds += 1
    remain = potato
  end
  seconds += remain / smashUnits
  remain %= smashUnits
}
seconds += 1 if remain > 0
puts seconds

$now = 0

$n, $h, $k = gets.chomp.split(' ').map { |i| i.to_i }
$potatos = gets.chomp.split(' ').map { |i| i.to_i }

def put_potato
	#puts "Before put_potato : #{$inQueue}"
	#puts "Now : #{$now}"

	until $inQueue + $potatos[$now] > $h
	#	puts "Now inQueue : #{$inQueue}"
		$inQueue += $potatos[$now]
		$now += 1

		break if $now == $potatos.length
	end

	#puts "After put_potato : #{$inQueue}"
end

time = 0
$inQueue = 0
put_potato

until $now == $potatos.length
	nn = ($inQueue / $k)
	time += nn
	time += 1 if nn == 0
	$inQueue -= (nn * $k)
	$inQueue = 0 if nn == 0
	put_potato
end

time += ($inQueue / $k)
time += 1 if ($inQueue % $k > 0)

puts time

now = 0

n, h, k = gets.chomp.split(' ').map { |i| i.to_i }
potatos = gets.chomp.split(' ').map { |i| i.to_i }

time = 0
remain = potatos[0]

i = 0

until i >= (potatos.length - 1)
	time += 1
	remain -= k
	#puts "Remain : #{remain}"
	#puts "Next potatos : #{potatos[i + 1]}"
	if remain + potatos[i + 1] <= h
		remain += potatos[i + 1]

	#puts "Insidle Remain : #{remain}"

		if remain < 0
			i += 1
			until remain >= 0
				#puts "Interpol Remain : #{remain}"
				break if i >= potatos.length
				remain += potatos[i + 1]
				i += 1
			end
		end
	else
		remain = potatos[i + 1]
		time += 1
	end

	i += 1
end

time += (remain / k)
time += 1 if remain % k > 0

puts time