Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.

For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.

NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.

gets.to_i.times do
  a = gets.chomp.split('').map{|c| c.ord - 'a'.ord + 1}
  s = a.inject(:+)
  if a.size % 2 == 0 then
    alice = s
    bob = 0
  else
    if a.size == 1 then
      bob = s
      alice = 0
    else
      bob = [a[0],a[a.size-1]].min
      alice = s - bob
    end
  end
  if alice > bob then
    puts "Alice #{alice-bob}"
  else
    puts "Bob #{bob-alice}"
  end
end

gets.to_i.times do
  s = gets.chomp
  chars = s.chars.map { |ch| ch.ord - 97 + 1 }
  alice, bob = if s.size.even?
      [chars.sum, 0]
    else
      min = [chars[0], chars[-1]].min
      [chars.sum - min, min]
    end
  puts "#{alice > bob ? "Alice" : "Bob"} #{(alice - bob).abs}"
end

t = gets.to_i
alphabet = " abcdefghijklmnopqrstuvwxyz"
f=->s{s.chars.sum{alphabet.index(_1)}}
t.times do |cas|
  s = gets.chomp
  if s.size%2==0
    puts "Alice %d"%[f[s]]
  else
    a = [f[s[1..]], f[s[..-2]]].max
    b = f[s] - a
    if a > b
      puts "Alice %d"%(a-b)
    else
      puts "Bob %d"%(b-a)
    end
  end
end

# (a+b+c)
# (bc + ac + ab) + ad + bd + cd = 0
# d(a+b+c) + e(a+b+c) = -(bc + ac + ab)
# d + e = -(bc + ac + ab + de) /(a+b+c)

gets.to_i.times do
  a = gets.chomp.split('').map{|c| c.ord - 'a'.ord + 1}
  s = a.inject(:+)
  puts s
  if a.size % 2 == 0 then
    puts "Alice #{s}"
  else
    if a.size == 1 then
      puts "Bob #{s}"
    else
      puts "Alice #{s - 2*[a[0],a[a.size-1]].min}"
    end
  end
end


Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.

In a single line print the answer to the problem — the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.

NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.

patterns = Array.new(gets.to_i){ gets.chomp }
pat = []
for i in 0...patterns[0].length
  sym = ''
  for j in 0...patterns.length
    if patterns[j][i] != '?' && sym != '?'
      if sym.length == 0
        sym = patterns[j][i]
      else
        if sym != patterns[j][i]
          sym = '?'
        end
      end
    end
  end
  pat << (sym.length == 0 ? 'x' : sym)
end

puts pat.join


There are $$$n$$$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $$$x$$$ be the number of such pairs of students in a split. Pairs $$$(a, b)$$$ and $$$(b, a)$$$ are the same and counted only once.For example, if there are $$$6$$$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:  splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $$$x=4$$$ ($$$3$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom),  splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $$$x=1$$$ ($$$0$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom). You are given the list of the $$$n$$$ names. What is the minimum $$$x$$$ we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

The first line contains a single integer $$$n$$$ ($$$1\leq n \leq 100$$$) — the number of students. After this $$$n$$$ lines follow. The $$$i$$$-th line contains the name of the $$$i$$$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $$$20$$$. Note that multiple students may share the same name.

The output must consist of a single integer $$$x$$$ — the minimum possible number of chatty pairs.

7
kambei
gorobei
shichiroji
kyuzo
heihachi
katsushiro
kikuchiyo

NoteIn the first sample the minimum number of pairs is $$$1$$$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is $$$2$$$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is $$$4$$$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom.

def sum(m)
	s = 0
	for i,k in m
		temp = k / 2
		s += temp * (temp-1) / 2
		s += (k-temp) * (k-temp-1) /2
	end
	return s
end

n = gets.to_i
m = Hash.new
m.default = 0
n.times do
	t = gets
	m[t[0]] += 1
end
puts(sum(m))

n = gets.to_i
cnt = Hash.new(0)
n.times do
  s = gets.chomp
  cnt[s[0]] += 1
end
ans = 0
cnt.each do |k,v|
  x = v/2 + v%2
  ans += x * (x-1) / 2
  ans += (v-x) * (v-x-1) /2
end
p ans

n = gets.to_i
a = Hash.new(0)
n.times do
    a[gets[0]] += 1
end
ans = 0
a.values.each do |i|
    ans += i/2*(i/2-1)/2+(i-i/2)*(i-i/2-1)/2
end
puts ans

def combinations(n)
  Math.gamma(n + 1) / (Math.gamma(3) * Math.gamma((n - 2) + 1))
end

students_count = gets.chomp
groups = {}

(1..students_count.to_i).each do |_n|
  name = gets.chomp
  groups[name[0]] = groups[name[0]] ? groups[name[0]] + 1 : 1
end

min = 0
groups.each_value do |count|
  next if count <= 2
  min += count.even? ? combinations(count / 2) * 2 : combinations(count / 2) + combinations((count / 2) + 1)
end

print min.to_i

def combinations(n)
  Math.gamma(n + 1) / (Math.gamma(3) * Math.gamma((n - 2) + 1))
end

students_count = gets.chomp
students = []
groups = {}

(1..students_count.to_i).each do |_n|
  name = gets.chomp
  students << name
  groups[name[0]] = groups[name[0]] ? groups[name[0]] + 1 : 1
end

min = 0
groups.each do |_char, count|
  next if count <= 2
  min += count.even? ? combinations(count / 2) * 2 : combinations(count / 2) + combinations((count / 2) + 1)
end

print min.to_i

def combi2(m)
  return m * (m-1) / 2
end

n = gets.to_i
students = {}
for i in 0...n do
  initial = gets.chomp[0]
  if students.include?(initial)
    students[initial] += 1
  else
    students[initial] = 1
  end
end
sum = 0
students.each_value { |num|
  sum += combi2((num + 1) / 2) + combi2(num / 2)
}

puts sum

def combi2(m)
  return m * (m-1) / 2
end

n = gets.to_i
students = {}
for i in 0...n do
  initial = gets.chomp[0]
  if students.include?(initial)
    students[initial] += 1
  else
    students[initial] = 1
  end
end
max = 0
students.each_value { |num|
  max = num if max < num
}

puts combi2((max + 1) / 2) + combi2(max / 2)


Nick had received an awesome array of integers $$$a=[a_1, a_2, \dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \cdot a_2 \cdot \dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \cdot a_2 \cdot \dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.

The first line contains integer $$$n$$$ ($$$1 \leq n \leq 10^{5}$$$) — number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^{6} \leq a_i \leq 10^{6}$$$) — elements of the array

Print $$$n$$$ numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.

n = gets.to_i
a = gets.split.map(&:to_i)
cnt = 0
maxi = 0
n.times do |i|
  a[i] = -a[i]-1 if a[i] >= 0
  cnt += 1 if a[i] < 0
  if a[i].abs > a[maxi].abs
    maxi = i
  end
end
if cnt % 2 == 0
  puts a.join(" ")
else
  a[maxi] = -a[maxi]-1
  puts a.join(" ")
end

n = gets.to_i
a = gets.split.map(&:to_i)
cnt = 0
maxi = 0
n.times do |i|
  a[i] = -a[i]-1 if a[i] >= 0
  cnt += 1 if a[i] < 0
  if a[i].abs > a[maxi]
    maxi = i
  end
end
if cnt % 2 == 0
  puts a.join(" ")
else
  a[maxi] = -a[maxi]-1
  puts a.join(" ")
end


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

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

a, b = gets.split.map &:to_i
c = a.gcd b
data = Array.new(c, nil)
x = gets.split.map &:to_i
x.shift
x.each {|_|
  data[_ % c] = true
}
x = gets.split.map &:to_i
x.shift
x.each {|_|
  data[_ % c] = true
}
puts data.all? ? "Yes" : "No"

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
_, *xs = gets.split.map(&:to_i)
_, *ys = gets.split.map(&:to_i)

x_happy = Array::new(n, false)
y_happy = Array::new(m, false)

xs.each { |i| x_happy[i] = true }
ys.each { |i| y_happy[i] = true }

(n*m*2).times do |i|
  if x_happy[i%n] || y_happy[i%m]
    x_happy[i%n] = y_happy[i%m] = true
  end
end

if x_happy.all? && y_happy.all?
  puts "Yes"
else
  puts "No"
end

def g;gets.split.map(&:to_i)end
UF=Hash.new{|_,k|k}
def u a,b;UF[f a]=UF[f b]end
def f c;c==UF[c]?c:UF[c]=f(UF[c])end
n,m=g
b,*x=g
c,*y=g
happy = x+y.map{|i|i+n}
if happy==[]
  puts "No"
else
  if happy.size>1
    happy[1..-1].each{|i|u happy[0],i}
  end
  10000.times{|i|u i%n,n+i%m}
  puts (0..n+m-1).map{|i|f i}.uniq.size==1?"Yes":"No"
end

#!/usr/bin/ruby

#read data
params = gets.split(' ').map(&:to_i)
n = params[0].to_i
m = params[1].to_i

params = gets.split(' ').map(&:to_i)
b = params.shift
happy_b = params

params = gets.split(' ').map(&:to_i)
g = params.shift
happy_g = params

#puts happy_b.to_s
#puts happy_g.to_s

boys = Array.new(size=n, default=0)
girls = Array.new(size=m, default=0)

happy_b.each do |e|
    boys[e] = 1;
end

happy_g.each do |e|
    girls[e] = 1;
end

#puts boys.to_s
#puts girls.to_s

res = false;
times_to_run  = n.lcm m #mua ha ha
counter = 0;
#puts times_to_run
while (counter < times_to_run && !res) do
    if (boys[counter % n] == 1 || girls[counter % m] == 1)
        if (boys[counter % n] == 1 && girls[counter % m] == 0)
            girls[counter % m] = 1;
            g = g + 1;
        elsif (boys[counter % n] == 0 && girls[counter % m] == 1)
            boys[counter % n] = 1;
            b = b + 1;
        end
    end

 #   puts 'Iteration ' + counter.to_s
 #   puts boys.to_s
 #   puts girls.to_s
 #   puts b,n,g,m
    counter = counter + 1
    if (b == n || g == m)
        res = true;
        break
    end
end

if res
    puts 'Yes'
else
    puts 'No'
end

n, m = gets.split.map(&:to_i)
lbs = gets.split.map(&:to_i).drop(1)
lgs = gets.split.map(&:to_i).drop(1)
ul = n + m - (lbs.count + lgs.count)
bs = Array.new(n, false)
lbs.each {|i| bs[i] = true}
gs = Array.new(m, false)
lgs.each {|i| gs[i] = true}
lasti = 0
for i in 0..Float::INFINITY do
  bi, gi = i%n, i%m
  if bs[bi] || gs[gi]
    ul -= 1 unless bs[bi]
    ul -= 1 unless gs[gi]
    lasti = i unless bs[bi] && gs[gi]
    bs[bi] = gs[gi] = true
  end
  break if ul == 0
  break if i - lasti > m*n
end
puts ul == 0 ? "Yes" : "No"

def create_list(n, hippies)
    result = []
    n.times do |i|
        result << hippies.include?(i)
    end
    result
end

nm = gets.chomp.split(' ').map{|i| i.to_i }
n = nm[0]
m = nm[1]
happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_b = if happy_amount > 0 then happy_ar[1..-1] else [] end
boys = create_list(n, happy_who_b)

happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_g = if happy_amount > 0 then happy_ar[1..-1] else [] end
girls = create_list(m, happy_who_g)

def check(n, m, boys, girls)
    # gcd = n.gcd(m)
    (n * m * 2).times do |i|
        if boys[i % boys.length] or girls[i % girls.length]
            boys[i % boys.length] = true
            girls[i % girls.length] = true
        end
    end
    return (boys.all? and girls.all?)
end

puts check(n, m, boys, girls) ? 'Yes' : 'No'

n, m = gets.split.map(&:to_i)
a =  Array.new(n).map{0}
b =  Array.new(m).map{0}
a1 = gets.split.map(&:to_i)
b1 = gets.split.map(&:to_i)
a1.each_with_index{|x, i|
if i != 0
  a[x] = 1
end
}
b1.each_with_index{|x, i|
  if i != 0
    b[x] = 1
  end
}
k1 = 0
k2 = 0
f1 = 0
f2 = 0
for i in 0..3000000
  it1 = i % n
  it2 = i % m
  #print(" it1 #{it1}    it2 #{it2} ")
  if(a[it1] == 1 || b[it2] == 1)
    if(a[it1] == 0)
      a[it1] = 1
      k1 += 1
    end
    if(b[it2] == 0)
      b[it2] = 1
      k2 += 1
    end
  end
    if(n - (a1[0] + k1) == 0)
   f1 = 1
  end
  if(m - (b1[0] + k2) == 0)
   f2 = 1
  end
  if f2 == 1 && f1 == 1
    break
  end
end
  if f2 == 1 && f1 == 1
    puts("Yes")
  else
    puts("No")
  end

pa=Array.new(105,0)
pb=Array.new(105,0)
pc=Array.new

str=gets.to_s
pc=str.split
n=pc[0].to_i
m=pc[1].to_i

k=n*m
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pa[pc[i].to_i]=1
end
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pb[pc[i].to_i]=1
end

for i in 0..k*2
  a=i%n
  b=i%m
  if pa[a]==1 || pb[b]==1
    pa[a]=pb[b]=1
  end
end

#for i in 0..n-1
#  puts pa[i]
#end
#puts
#for i in 0..m-1
#  puts pb[i]
#end

h=0
for i in 0..n-1
  if pa[i]==0
    h=1
    break
  end
end

for i in 0..m-1
  if pb[i]==0 || h==1
    h=1
    break
  end
end

if h==1
  puts "No"
elsif h==0
  puts "Yes"
end

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

a.delete_at(0)
b.delete_at(0)

h1 = []
h2 = []

(0..(n+m)).each {|x|
  h1 << 0
  h2 << 0
}

a.each { |x| h1[x] = 1 }
b.each { |x| h2[x] = 1 }

(0..(n*m*2)).each {|x|
  if h1[x % n] == 1 || h2[x % m] == 1
    h1[x % n] = 1
    h2[x % m] = 1
  end
}

res = 0
(0..(n-1)).each {|x| res = 1 if h1[x] == 0}
(0..(m-1)).each {|x| res = 1 if h2[x] == 0}

if res == 1
  puts "No"
else
  puts "Yes"
end

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
xs = gets.split.map(&:to_i)
ys = gets.split.map(&:to_i)

x_happy = Array::new(n, false)
y_happy = Array::new(m, false)

xs[1, xs[0]].each do |x|
  x_happy[x] = true
end

ys[1, ys[0]].each do |y|
  y_happy[y] = true
end

g = n.gcd(m)

(n*m*2).times do |i|
  if x_happy[i%n] && y_happy[i%m]
    x_happy[i%n] = y_happy[i%m] = true
  end
end

if x_happy.all? && y_happy.all?
  puts "Yes"
else
  puts "No"
end

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
xs = gets.split.map(&:to_i)
ys = gets.split.map(&:to_i)

x_happy = Array::new(n, false)
y_happy = Array::new(m, false)

xs[1, xs[0]].each do |x|
  x_happy[x] = true
end

ys[1, ys[0]].each do |y|
  y_happy[y] = true
end

g = n.gcd(m)

[x_happy.length, y_happy.length].min.times {
  x_happy.length.times do |i|
    y_happy.length.times do |j|
      if (i - j).abs % g == 0 && (x_happy[i] || y_happy[j])
        x_happy[i] = y_happy[j] = true
      end
    end
  end
}

if x_happy.all? && y_happy.all?
  puts "Yes"
else
  puts "No"
end

#!/usr/bin/ruby

#read data
params = gets.split(' ').map(&:to_i)
n = params[0].to_i
m = params[1].to_i

params = gets.split(' ').map(&:to_i)
b = params.shift
happy_b = params

params = gets.split(' ').map(&:to_i)
g = params.shift
happy_g = params

boys = Array.new(size=n, default=0)
girls = Array.new(size=m, default=0)

happy_b.each do |e|
    boys[e] = 1;
end

happy_g.each do |e|
    girls[e] = 1;
end

#puts boys.to_s
#puts girls.to_s

res = false;
times_to_run  = n.lcm m #mua ha ha
counter = 0;
#puts times_to_run
while (counter < times_to_run && !res) do
    if (boys[counter % n] == 1 || girls[counter % m] == 1)
        if (boys[counter % n] == 1 && girls[counter % m] == 0)
            girls[counter % m] = 1;
            g = g + 1;
        elsif (boys[counter % n] == 0 && girls[counter % m] == 1)
            boys[counter % m] = 1;
            b = b + 1;
        end
    end

   # puts 'Iteration ' + counter.to_s
   # puts boys.to_s
   # puts girls.to_s
    counter = counter + 1
    if (b == n || g == m)
        res = true;
    end
end

if res
    puts 'Yes'
else
    puts 'No'
end

n, m = gets.split.map(&:to_i)
lbs = gets.split.map(&:to_i).drop(1)
lgs = gets.split.map(&:to_i).drop(1)
ul = n*m - (lbs.count + lgs.count)
bs = Array.new(n, false)
lbs.each {|i| bs[i] = true}
gs = Array.new(m, false)
lgs.each {|i| gs[i] = true}
for i in 0...n*m do
  bi, gi = i%n, i%m
  break if i > 0 && bi == 0 && gi == 0
  if bs[bi] || gs[gi]
    ul -= 1 unless bs[bi]
    ul -= 1 unless gs[gi]
    bs[bi] = gs[gi] = true
  end
  break if ul == 0
end
puts ul == 0 ? "Yes" : "No"

n, m = gets.split.map(&:to_i)
lbs = gets.split.map(&:to_i).drop(1)
lgs = gets.split.map(&:to_i).drop(1)
ul = n + m - (lbs.count + lgs.count)
bs = Array.new(n, false)
lbs.each {|i| bs[i] = true}
gs = Array.new(m, false)
lgs.each {|i| gs[i] = true}
for i in 0...n*m do
  bi, gi = i%n, i%m
  if bs[bi] || gs[gi]
    ul -= 1 unless bs[bi]
    ul -= 1 unless gs[gi]
    bs[bi] = gs[gi] = true
  end
  break if ul == 0
end
puts ul == 0 ? "Yes" : "No"

n, m = gets.split.map(&:to_i)
lbs = gets.split.map(&:to_i).drop(1)
lgs = gets.split.map(&:to_i).drop(1)
ul = n*m - (lbs.count + lgs.count)
bs = Array.new(n, false)
lbs.each {|i| bs[i] = true}
gs = Array.new(m, false)
lgs.each {|i| gs[i] = true}
for i in 0...n*m do
  bi, gi = i%n, i%m
  if bs[bi] || gs[gi]
    ul -= 1 unless bs[bi]
    ul -= 1 unless gs[gi]
    bs[bi] = gs[gi] = true
  end
  break if ul == 0
end
puts ul == 0 ? "Yes" : "No"

n, m = gets.split.map(&:to_i)
lbs = gets.split.map(&:to_i).drop(1)
lgs = gets.split.map(&:to_i).drop(1)
ul = n + m - (lbs.count + lgs.count)
bs = Array.new(n, false)
lbs.each {|i| bs[i] = true}
gs = Array.new(m, false)
lgs.each {|i| gs[i] = true}
for i in 0...n*m do
  bi, gi = i%n, i%m
  break if i > 0 && bi == 0 && gi == 0
  if bs[bi] || gs[gi]
    ul -= 1 unless bs[bi]
    ul -= 1 unless gs[gi]
    bs[bi] = gs[gi] = true
  end
  break if ul == 0
end
puts ul == 0 ? "Yes" : "No"

def create_list(n, hippies)
    result = []
    n.times do |i|
        result << hippies.include?(i)
    end
    result
end

nm = gets.chomp.split(' ').map{|i| i.to_i }
n = nm[0]
m = nm[1]
happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_b = if happy_amount > 0 then happy_ar[1..-1] else [] end
boys = create_list(n, happy_who_b)

happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_g = if happy_amount > 0 then happy_ar[1..-1] else [] end
girls = create_list(m, happy_who_g)

def check(n, m, boys, girls, hboys, hgirls)
    # special case: if Drazil have the same number of girls and boys then
    # true would be only if in pairs at least one of them is happy
    if n == m
        n.times do |i|
            return false if not boys[i] and not girls[i]
        end
        return true
    end
    if (n-m).abs % 2 == 1
        return true
    end
    even = hboys.any?{|x| x % 2 == 0} or hgirls.any?{|x| x % 2 == 0}
    odd = hboys.any?{|x| x % 2 == 1} or hgirls.any?{|x| x % 2 == 1}
    return (even and odd)
end

puts check(n, m, boys, girls, happy_who_b, happy_who_g) ? 'Yes' : 'No'

def create_list(n, hippies)
    result = []
    n.times do |i|
        result << hippies.include?(i)
    end
    result
end

nm = gets.chomp.split(' ').map{|i| i.to_i }
n = nm[0]
m = nm[1]
happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_b = if happy_amount > 0 then happy_ar[1..-1] else [] end
boys = create_list(n, happy_who_b)

happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_g = if happy_amount > 0 then happy_ar[1..-1] else [] end
girls = create_list(m, happy_who_g)

def check(n, m, boys, girls)
    gcd = n.gcd(m)
    ((boys.length * girls.length) / gcd).times do |i|
        if boys[i % boys.length] or girls[i % girls.length]
            boys[i % boys.length] = true
            girls[i % girls.length] = true
        end
    end
    return (boys.all?{|x| x} and girls.all?{|x| x})
end

puts check(n, m, boys, girls) ? 'Yes' : 'No'

def create_list(n, hippies)
    result = []
    n.times do |i|
        result << hippies.include?(i)
    end
    result
end

nm = gets.chomp.split(' ').map{|i| i.to_i }
n = nm[0]
m = nm[1]
happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_b = if happy_amount > 0 then happy_ar[1..-1] else [] end
boys = create_list(n, happy_who_b)

happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_g = if happy_amount > 0 then happy_ar[1..-1] else [] end
girls = create_list(m, happy_who_g)

def check(n, m, boys, girls)
    gcd = n.gcd(m)
    if (n - m).abs % gcd != 0
        return true
    end
    ((boys.length * girls.length) / gcd).times do |i|
        if boys[i % boys.length] or girls[i % girls.length]
            boys[i % boys.length] = true
            girls[i % girls.length] = true
        end
    end
    return (boys.all?{|x| x} and girls.all?{|x| x})
end

puts check(n, m, boys, girls) ? 'Yes' : 'No'

def create_list(n, hippies)
    result = []
    n.times do |i|
        result << hippies.include?(i)
    end
    result
end

nm = gets.chomp.split(' ').map{|i| i.to_i }
n = nm[0]
m = nm[1]
happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_b = if happy_amount > 0 then happy_ar[1..-1] else [] end
boys = create_list(n, happy_who_b)

happy_ar = gets.chomp.split(' ').map{|i| i.to_i }
happy_amount = happy_ar[0]
happy_who_g = if happy_amount > 0 then happy_ar[1..-1] else [] end
girls = create_list(m, happy_who_g)

def check(n, m, boys, girls)
    # gcd = n.gcd(m)
    (boys.length * girls.length).times do |i|
        if boys[i % boys.length] or girls[i % girls.length]
            boys[i % boys.length] = true
            girls[i % girls.length] = true
        end
    end
    return (boys.all?{|x| x} and girls.all?{|x| x})
end

puts check(n, m, boys, girls) ? 'Yes' : 'No'

pa=Array.new(105,0)
pb=Array.new(105,0)
pc=Array.new

str=gets.to_s
pc=str.split
n=pc[0].to_i
m=pc[1].to_i

k=n*m
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pa[pc[i].to_i]=1
end
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pb[pc[i].to_i]=1
end

for i in 0..k
  a=i%n
  b=i%m
  if pa[a]==1 || pb[b]==1
    pa[a]=pb[b]=1
  end
end

h=0
for i in 0..n-1
  if pa[i]==0
    h=1
    break
  end
end

for i in 0..m-1
  if pb[i]==0 || h==1
    h=1
    break
  end
end

if h==1
  puts "No"
elsif h==0
  puts "Yes"
end

pa=Array.new(105,0)
pb=Array.new(105,0)
pc=Array.new

str=gets.to_s
pc=str.split
n=pc[0].to_i
m=pc[1].to_i

k=n*m
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pa[pc[i].to_i]=1
end
str=gets.to_s
pc=str.split
b=pc[0].to_i
for i in 1..b
  pb[pc[i].to_i]=1
end

for i in 0..n-1
  puts pa[i]
end
for i in 0..m-1
  puts pb[i]
end

for i in 0..k
  a=i%n
  b=i%m
  if pa[a]==1 || pb[b]==1
    pa[a]=pb[b]=1
  end
end

h=0
for i in 0..n-1
  if pa[i]==0
    h=1
    break
  end
end

for i in 0..m-1
  if pb[i]==0 || h==1
    h=1
    break
  end
end

if h==1
  puts "No"
elsif h==0
  puts "Yes"
end

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

a.delete_at(0)
b.delete_at(0)

h1 = []
h2 = []

(0..(n+m)).each {|x|
  h1 << 0
  h2 << 0
}

a.each { |x| h1[x] = 1 }
b.each { |x| h2[x] = 1 }

(0..(n*m)).each {|x|
  if h1[x % n] == 1 || h2[x % m] == 1
    h1[x % n] = 1
    h2[x % m] = 1
  end
}

res = 0
(0..(n-1)).each {|x| res = 1 if h1[x] == 0}
(0..(m-1)).each {|x| res = 1 if h2[x] == 0}

if res == 1
  puts "No"
else
  puts "Yes"
end


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 2 \cdot 10^{5})$$$ — the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \dots, b_m$$$ $$$(1 \le b_j \le a_1 + a_2 + \dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.

Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ — the dormitory number $$$f$$$ $$$(1 \le f \le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \le k \le a_f)$$$ to deliver the letter.

NoteIn the first example letters should be delivered in the following order:  the first letter in room $$$1$$$ of the first dormitory  the second letter in room $$$9$$$ of the first dormitory  the third letter in room $$$2$$$ of the second dormitory  the fourth letter in room $$$13$$$ of the second dormitory  the fifth letter in room $$$1$$$ of the third dormitory  the sixth letter in room $$$12$$$ of the third dormitory

sum = 0
ca = {}

def search (n, b, ca)
  lo, hi, ans = 1, n
  while lo <= hi
    md = (lo + hi) / 2
    if ca[md] >= b
      ans = md
      hi = md - 1
    else
      lo = md + 1
    end
  end
  "#{ans} #{(b - ca[ans - 1])}"
end

n, m = gets.split(" ")
a = [0] + gets.split(" ")
b = [0] + gets.split(" ")
a.each_with_index {|cnt, index| ca[index] = (sum += cnt.to_i)}
(1..(m.to_i)).each { |i| puts search(n.to_i, b[i].to_i, ca)}


Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.

The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.

Print the only integer — the answer to the problem.

NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.

#f = File.open("c.in", "r")
class C <
	Struct.new(:ai, :bi)
end

n = gets.to_i
a = Array.new

for i in 0...n
	l = gets.split
	c = C.new
	c.ai = l[0].to_i
	c.bi = l[1].to_i
	a.push(c)
end

a = a.sort {|o, p| o[:ai] <=> p[:ai]}
m = r = 0

for i in 0...n
	m = [m, a[i].bi].max
	if a[i].bi < m
		r += 1
	end
end

puts r

def run(input = STDIN.read)
  periods = input.split("\n")[1..-1].map { |row| row.split.map(&:to_i) }

  periods.sort_by!(&:first)

  current_max = periods.first.last
  res = 0
  periods[1..-1].each do |period|
    res += 1 if period.last < current_max
    current_max = period.last if period.last > current_max
  end

  puts res
end

run

def history
  coord = []
  STDIN.gets.to_i.times { coord << gets.split(' ').map{|i| i.to_i} }
  coord.sort!{|x, y| y[1] <=> x[1] }

  if coord.size < 2
    puts 0
    return
  end

  tot = 0
  min = coord[0][0]
  (1...coord.size).each do |ind|
    c = coord[ind]
    if c[0] > min
      tot += 1
    else
      min = c[0]
    end
  end
  p tot
end

history

n = gets.to_i
arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
end

arr.sort!#_by!{|x| [x[0],-x[1]]}

count = 0
max  = -1
arr.map(&:last).each do |a|

	if a < max
		count += 1
	else
		max = a
	end
end
puts count

require "set"
n = gets.chomp.to_i
events = []
events2 = []
n.times do
  e = gets.chomp.split(" ").map {|e| e.to_i}
  events.push e
end

total = 0
events = events.sort_by {|e| e[0]}
largest = 0

events.each do |e|
  if largest > e[1]
    total += 1
  end
  if e[1] > largest
    largest = e[1]
  end
end

puts total

def history
  coord = []
  STDIN.gets.to_i.times { coord << gets.split(' ').map{|i| i.to_i} }
  coord.sort!{|x, y| y[1] <=> x[1] }

  if coord.size < 2
    puts 0
    return
  end

  ind = 1
  max = coord[0][1]
  ind += 1 while coord[ind][1] >= max
  puts coord.size-ind
end

history

n = gets.to_i
arr = []
n.times do
	arr << gets.split(" ").map(&:to_i)
end

arr.sort_by!{|x| [x[0],-x[1]]}

range_arr = []
count = 0
arr.each do |a|
	found = false
	if range_arr.any?{ |b|  a[0] > b[0] && a[1] < b[1] }
		found = true
		count += 1
		break
	end
	range_arr << a unless found
end
puts count


Let's denote the Manhattan distance between two points $$$p_1$$$ (with coordinates $$$(x_1, y_1)$$$) and $$$p_2$$$ (with coordinates $$$(x_2, y_2)$$$) as $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$$$. For example, the distance between two points with coordinates $$$(1, 3)$$$ and $$$(4, 2)$$$ is $$$|1 - 4| + |3 - 2| = 4$$$.You are given two points, $$$A$$$ and $$$B$$$. The point $$$A$$$ has coordinates $$$(0, 0)$$$, the point $$$B$$$ has coordinates $$$(x, y)$$$.Your goal is to find a point $$$C$$$ such that:  both coordinates of $$$C$$$ are non-negative integers;  $$$d(A, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding);  $$$d(B, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding). Find any point $$$C$$$ that meets these constraints, or report that no such point exists.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the point $$$B$$$.

For each test case, print the answer on a separate line as follows:   if it is impossible to find a point $$$C$$$ meeting the constraints, print "-1 -1" (without quotes);  otherwise, print two non-negative integers not exceeding $$$10^6$$$ — the coordinates of point $$$C$$$ meeting the constraints. If there are multiple answers, print any of them. It can be shown that if any such point exists, it's possible to find a point with coordinates not exceeding $$$10^6$$$ that meets the constraints.

NoteExplanations for some of the test cases from the example:  In the first test case, the point $$$B$$$ has coordinates $$$(49, 3)$$$. If the point $$$C$$$ has coordinates $$$(23, 3)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|49 - 0| + |3 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|23 - 0| + |3 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|23 - 49| + |3 - 3| = 26$$$.  In the second test case, the point $$$B$$$ has coordinates $$$(2, 50)$$$. If the point $$$C$$$ has coordinates $$$(1, 25)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|2 - 0| + |50 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|1 - 0| + |25 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|1 - 2| + |25 - 50| = 26$$$.  In the third and the fourth test cases, it can be shown that no point with integer coordinates meets the constraints.  In the fifth test case, the point $$$B$$$ has coordinates $$$(42, 0)$$$. If the point $$$C$$$ has coordinates $$$(21, 0)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|42 - 0| + |0 - 0| = 42$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|21 - 0| + |0 - 0| = 21$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|21 - 42| + |0 - 0| = 21$$$.

gets
$<.map do
  x,y=_1.split.map &:to_i
  if (x+y).odd?
    puts "-1 -1"
  elsif x.even?
    puts [x/2,y/2]*" "
  else
    puts (x>y ? [x/2+1,y/2]*" " : [x/2,y/2+1]*" ")
  end
end

gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  diff = (x - y).abs
  if diff.even?
    if x > y
      puts "#{diff / 2} #{y}"
    else
      puts "#{x} #{diff / 2}"
    end
  else
    puts "-1 -1"
  end
end

main = -> {
  t = int
  t.times do
    x, y = ints
    if (x + y).odd?
      puts "-1 -1"
    else
      a, b = x.div_ceil(2), y / 2
      puts "#{a} #{b}"
      # STDERR.puts "#{a+b} == #{(x - a).abs + (y - b).abs}"
    end
  end
}

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

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 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
$<.map do
  x,y=_1.split.map &:to_i
  if (x+y).odd?
    puts "-1 -1"
  elsif x.even?
    puts [x/2,y/2]*" "
  else
    x,y=y,x if x<y
    puts [x/2+1,y/2]*" "
  end
end

gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  min, max = [x, y].min, [x, y].max
  diff = max - min
  if diff.even?
    puts "#{min} #{diff / 2}"
  else
    puts "-1 -1"
  end
end


A sequence of positive integers is called great for a positive integer $$$x$$$, if we can split it into pairs in such a way that in each pair the first number multiplied by $$$x$$$ is equal to the second number. More formally, a sequence $$$a$$$ of size $$$n$$$ is great for a positive integer $$$x$$$, if $$$n$$$ is even and there exists a permutation $$$p$$$ of size $$$n$$$, such that for each $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$) $$$a_{p_{2i-1}} \cdot x = a_{p_{2i}}$$$. Sam has a sequence $$$a$$$ and a positive integer $$$x$$$. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence $$$a$$$ to make it great for the number $$$x$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le x \le 10^6$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the minimum number of integers that can be added to the end of $$$a$$$ to make it a great sequence for the number $$$x$$$.

NoteIn the first test case, Sam got lucky and the sequence is already great for the number $$$4$$$ because you can divide it into such pairs: $$$(1, 4)$$$, $$$(4, 16)$$$. Thus we can add $$$0$$$ numbers.In the second test case, you can add numbers $$$1$$$ and $$$14$$$ to the sequence, then you can divide all $$$8$$$ integers into such pairs: $$$(1, 2)$$$, $$$(1, 2)$$$, $$$(2, 4)$$$, $$$(7, 14)$$$. It is impossible to add less than $$$2$$$ integers to fix the sequence.

gets.to_i.times do
  n, x = gets.chomp.split.map(&:to_i)
  as = gets.chomp.split.map(&:to_i).tally
  answer = 0
  as.keys.sort.each do |a|
    ax = a * x
    while as[a] > 0
      as[a] -= 1
      if as[ax] && as[ax] > 0
        as[ax] -= 1
      else
        answer += 1
      end
    end
  end
  p answer
end


Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.

Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.

If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.

PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ

BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD

puts 'Impossible' if
[*$<].map(&:chomp).permutation(6) do |a,b,c,d,e,f|
    if a[0]==d[0] && a[-1]==e[0] &&
      c[0]==e[-1] && c[-1]==f[-1] &&
      b[0]==d[-1] && b[-1]==f[0] &&
      b[a.size-1]==e[d.size-1] &&
      a.size+c.size-1==b.size &&
      d.size+f.size-1==e.size
        puts a.ljust(b.size,'.')
        d[1...-1].chars.zip(e[1...-1].chars).map do |i,j|
            s = '.'*b.size
            s[0] = i
            s[a.size-1] = j
            puts s
        end
        puts b
        f[1...-1].chars.zip(e[d.size...-1].chars).map do |i,j|
            s = '.'*b.size
            s[a.size-1] = j
            s[-1] = i
            puts s
        end
        puts c.rjust(b.size,'.')
        break
    end
end


William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.

NoteIn the first test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements:   swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$  swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$  swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$  swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$

t = gets.to_i
t.times do

n = gets.to_i
a = gets.split.map!(&:to_i)

a.map! { |ai| ai & 1 }
a.map! { |ai| ai ^ 1 } if a[0] == 1

z = a.count(&:zero?)
if (n - z - z).abs >= 2
  puts -1
  next
end

s = a.join

i = -1
j1 = 0
j2 = 1
cnt1 = 0
cnt2 = 0
while true
  i2 = s.index('0', i + 1)
  break unless i2

  cnt1 += (j1 - i2).abs
  cnt2 += (j2 - i2).abs
  j1 += 2
  j2 += 2

  i = i2
end

if z < n - z
  puts cnt2
elsif z > n - z
  puts cnt1
else
  puts [cnt1, cnt2].min
end

end

t = gets.to_i
t.times do

n = gets.to_i
a = gets.split.map!(&:to_i)

a.map! { |ai| ai & 1 }
a.map! { |ai| ai ^ 1 } if a[0] == 1

z = a.count(&:zero?)
if z < n / 2 || n - z < n / 2
  puts -1
  next
end

s = a.join

i = -1
j = 0
j += 1 if z < n - z
cnt = 0
while true
  i2 = s.index('0', i + 1)
  break unless i2

  cnt += (j - i2).abs
  j += 2

  i = i2
end

puts cnt

end


Pak Chanek has $$$n$$$ two-dimensional slices of cheese. The $$$i$$$-th slice of cheese can be represented as a rectangle of dimensions $$$a_i \times b_i$$$. We want to arrange them on the two-dimensional plane such that:  Each edge of each cheese is parallel to either the x-axis or the y-axis.  The bottom edge of each cheese is a segment of the x-axis.  No two slices of cheese overlap, but their sides can touch.  They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of slices of cheese Pak Chanek has. The $$$i$$$-th of the next $$$n$$$ lines of each test case contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i,b_i \leq 10^9$$$) — the dimensions of the $$$i$$$-th slice of cheese. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a line containing an integer representing the minimum possible perimeter of the constructed shape.

NoteIn the first test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+5+1+1+1+1+3+1+5+1+2+3=26$$$. It can be shown that we cannot get a smaller perimeter.Consider the following invalid arrangement.Even though the perimeter of the shape above is $$$24$$$, it does not satisfy all conditions of the problem. The bottom edge of the $$$1 \times 1$$$ slice of cheese is not a segment of the x-axis.In the second test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+2+2+3+2+3+2+2+2+4=24$$$. It can be shown that we cannot get a smaller perimeter.

t=gets.to_i
t.times do
    n=gets.to_i
    l,m=0,0
    n.times do
        x,y=gets.chomp.split(' ').map(&:to_i)
        m=[m,x,y].max
        l+=[x,y].min
    end
    puts l*2+m*2
end


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$.Let $$$\operatorname{MEX}$$$ of a binary string be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the string. For example, $$$\operatorname{MEX}$$$ of $$$001011$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the string at least once, $$$\operatorname{MEX}$$$ of $$$1111$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the string and $$$0 < 2$$$.A binary string $$$s$$$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.What is the minimal sum of $$$\operatorname{MEX}$$$ of all substrings pieces can be?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single binary string $$$s$$$ ($$$1 \le |s| \le 10^5$$$). It's guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal sum of $$$\operatorname{MEX}$$$ of all substrings that it is possible to get by cutting $$$s$$$ optimally.

NoteIn the first test case the minimal sum is $$$\operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1$$$.In the second test case the minimal sum is $$$\operatorname{MEX}(1111) = 0$$$.In the third test case the minimal sum is $$$\operatorname{MEX}(01100) = 2$$$.

t = gets.to_i
t.times do

s = gets.chomp

a = s.scan(/0++|1++/).map { |ss| ss[0].to_i }

if a.size == 1
  puts (a[0] == 1) ? 0 : 1
  next
end

if a.size == 2
  puts 1
  next
end

if a.size == 3
  puts (a[0] == 1) ? 1 : 2
  next
end

puts 2

end


Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?

The first line contains a single integer n (1 ≤ n ≤ 105).

If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c. If there are multiple solutions, print any of them.

NoteIn Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds:  ;  ;  ;  ;  . In Sample 2, you can easily notice that no lucky permutation triple exists.

n=gets.to_i
if n.odd?
    a=[*0..n-1]
    puts a*' '
    puts (b=a.rotate)*' '
    c=[]
    a.each_with_index {|v, i| c<<(v+b[i])%n }
    puts c*' '
else
    puts -1
end

n = gets.to_i

a = (0...n).to_a

if n%2==0
  puts -1
elsif n%3!=0
  b = a.map {|x| (2*x)%n}
  c = a.map {|x| (x+(2*x)%n)%n}
  puts a.join(" ")
  puts b.join(" ")
  puts c.join(" ")
else
  b = a.map {|x| x%n}
  c = a.map {|x| (x*2)%n}
  puts a.join(" ")
  puts b.join(" ")
  puts c.join(" ")
end

n = gets.to_i
if n % 2 == 0
    puts -1
else
    a = []
    b = []
    c = []
    for i in 0...n
        a.push i
        b.push i
        c.push (i + i) % n
    end
    [a, b, c].each do |arr| puts arr.join(' ') end
end

n = gets.to_i

a = (0...n).to_a
b = a.map {|x| (2*x)%n}
c = a.map {|x| (x+(2*x)%n)%n}

if n%2==0
  puts -1
else
  puts a.join(" ")
  puts b.join(" ")
  puts c.join(" ")
end


You are given an array $$$a$$$ of length $$$n$$$. The array is called 3SUM-closed if for all distinct indices $$$i$$$, $$$j$$$, $$$k$$$, the sum $$$a_i + a_j + a_k$$$ is an element of the array. More formally, $$$a$$$ is 3SUM-closed if for all integers $$$1 \leq i < j < k \leq n$$$, there exists some integer $$$1 \leq l \leq n$$$ such that $$$a_i + a_j + a_k = a_l$$$.Determine if $$$a$$$ is 3SUM-closed.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output "YES" (without quotes) if $$$a$$$ is 3SUM-closed and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, there is only one triple where $$$i=1$$$, $$$j=2$$$, $$$k=3$$$. In this case, $$$a_1 + a_2 + a_3 = 0$$$, which is an element of the array ($$$a_2 = 0$$$), so the array is 3SUM-closed.In the second test case, $$$a_1 + a_4 + a_5 = -1$$$, which is not an element of the array. Therefore, the array is not 3SUM-closed.In the third test case, $$$a_i + a_j + a_k = 0$$$ for all distinct $$$i$$$, $$$j$$$, $$$k$$$, and $$$0$$$ is an element of the array, so the array is 3SUM-closed.

require 'set'
# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  great = a.count{|e| e > 0}
  less = a.count{|e| e < 0}

  if great > 2 || less > 2
    puts "NO"
  else
    zero = a.count(0)
    a = (a.select{|e| e != 0}) || []
    a += ([0] * [3, zero].min)
    s = Set.new
    ok = true
    n = a.size
    n.times do |i|
      i.times do |j|
        j.times do |k|
          s << a[i] + a[j] + a[k]
        end
      end
    end

    puts s.all?{|e| a.include?(e) } ? "YES" : "NO"
  end

end

require 'set'
# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = Set.new
  at = a.tally
  if n <= 5
    ok = true
    n.times do |i|
      i.times do |j|
        j.times do |k|
          s << a[i] + a[j] + a[k]
        end
      end
    end
    puts s.all?{|e| a.include?(e)} ? "YES" : "NO"
  elsif at[0]
    if at.size == 1 || at.size == 2
      puts "YES"
    elsif at.size == 3
      ok = true
      at.each_key do |k|
        next if k == 0
        ok = false if at[k] > 1
      end
      puts ok ? "YES" : "NO"
    end
  else
    puts "NO"
  end
end

require 'set'
# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  # ans = Set.new
  # n.times do |i|
  #   n.times do |j|
  #     n.times do |k|
  #       next if i == j || j == k || k == i
  #       ans << a[i]+a[j]+a[k]
  #     end
  #   end
  # end
  # p ans
  at = a.tally
  if at[0]
    if at.size == 1 || at.size == 2
      puts "YES"
    elsif at.size == 3
      ok = true
      at.each_key do |k|
        next if k == 0
        ok = false if at[k] > 1
      end
      puts ok ? "YES" : "NO"
    end
  elsif at.size <= 4
    ok = true
    at.each_key do |k|
      if at[-k].nil? || at[k] != at[-k]
        break ok = false
      end
    end
    puts ok ? "YES" : "NO"
  else
    puts "NO"
  end
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  at = a.tally
  if at[0]
    if at.size == 1 || at.size == 2
      puts "YES"
    elsif at.size == 3
      ok = true
      at.each_key do |k|
        next if k == 0
        ok = false if at[k] > 1
      end
      puts ok ? "YES" : "NO"
    end
  else
    ok = true
    at.each_key do |k|
      if at[-k].nil? || at[k] != at[-k]
        break ok = false
      end
    end
    puts ok ? "YES" : "NO"
  end
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  if n == 3
    if a.include?(a.sum)
      next puts "YES"
    else
      next puts "NO"
    end
  end

  at = a.tally
  if !at[0].nil?
    if at.size == 1 || at.size == 2
      next puts "YES"
    elsif at.size == 3
      ok = true
      at.each_key do |k|
        next if k == 0
        ok = false if at[k] > 1
      end
      next puts ok ? "YES" : "NO"
    end
  else
    at.each_key do |k|
      if at[-k].nil? || at[k] != at[-k]
        break ok = false
      end
    end
    puts ok ? "YES" : "NO"
  end
end


Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.

The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.

In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.

NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".

n,deg,s,que,sum=gets.to_i,[],[],[],0
(0...n).each do |i|
  deg[i],s[i]=gets.split.map &:to_i
  sum+=deg[i]
  que.push i if deg[i]==1
end
p sum/2
while que[0]
  f=que[-1]
  que.pop
  next if deg[f]==0
  puts [f,s[f]].join' '
  deg[s[f]]-=1
  s[s[f]]^=f
  que.push s[f] if deg[s[f]]==1
end

n=gets.to_i
deg,s,que,sum=[],[],[],0
(0..n-1).each do |i|
  deg[i],s[i]=gets.split.map(&:to_i)
  sum+=deg[i]
  if deg[i]==1
    que.push i
  end
end
puts sum/2
while que[-1]
  f=que[-1]
  que.pop
  if deg[f]==0
    next
  end
  print f,' ',s[f],"\n"
  deg[s[f]]-=1
  deg[f]-=1
  s[s[f]]^=f
  if deg[s[f]]==1
    que.push s[f]
  end
end

n=gets.to_i
deg,s,que,sum=[],[],[],0
(0..n-1).each do |i|
  deg[i],s[i]=gets.split.map(&:to_i)
  sum+=deg[i]
  if deg[i]==1
    que.push i
  end
end
p sum/2
while que[-1]
  f=que[-1]
  que.pop
  if deg[f]==0
    next
  end
  print f,' ',s[f],' '
  deg[s[f]]-=1
  deg[f]-=1
  s[s[f]]^=f
  if deg[s[f]]==1
    que.push s[f]
  end
end

n=gets.to_i
deg,s,que,sum=[],[],[],0
(0..n-1).each{|i| deg[i],s[i]=gets.split.map(&:to_i)}
deg.each_with_index do |i,id|
  if(i==1)
    que.push id
  end
  sum+=i
end
puts sum/2
while que[-1]
  f=que[-1]
  que.pop
  if deg[f]==0
    next
  end
  print f,' ',s[f]
  puts
  deg[s[f]]-=1
  deg[f]-=1
  s[s[f]]^=f
  if deg[s[f]]==1
    que.push s[f]
  end
end

n=gets.to_i
deg,s,que,sum=[],[],[],0
(0..n-1).each do |i|
  deg[i],s[i]=gets.split.map &:to_i
  sum+=deg[i]
  if deg[i]==1
    que.push i
  end
end
p sum/2
while que[0]
  f=que[-1]
  que.pop
  if deg[f]==0
    next
  end
  puts [f,s[f]].join' '
  deg[s[f]]-=1
  s[s[f]]^=f
  if deg[s[f]]==1
    que.push s[f]
  end
end


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

ns,ms= gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i

sa = gets.chomp.split(/ /)
sa.map!{|x| x.to_i}

sum = 0

sa.sort!
for i in 0..m-1
	sum += sa[i] if sa[i] < 0
end

puts -sum

n,m=gets.split.map(&:to_i)
v=[]
gets.split.map{|i|
	i=i.to_i
	if i<0 then
		v << i
	end
}
v.sort!
ans=0
[m,v.size].min.times{|i|
	ans-=v[i]
}
p ans

a = gets.chop.split(/ /)
a.map! do |i|
i = i.to_i
end

b = gets.chop.split(/ /)
b.map! do |i|
i = i.to_i
end

$cnt=0
$tmp = Array.new
for i in 0..(b.size-1)
if b[i] < 0
$tmp[$cnt] = i
$cnt=$cnt + 1
end
end

$sum = 0
if $cnt <= a[1]
$tmp.each do |i|
$sum=$sum - b[i]
end
else
b.sort!
for i in 0..a[1]-1
$sum=$sum - b[i]
end
end

puts $sum

m,n=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i).sort
t,i=0,0
while n!=0
	t+=a[i] if a[i]<0
	n-=1
	i+=1
end
puts -t

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort.find_all {|x| x < 0 }
puts (sc = a.first([a.size, m].min).inject(:+)).nil? ? 0 : -sc

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}.sort
ans=0
m.times{|i|
	ans-=x[i] if x[i]<=0
}
puts ans

#=================================
if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open(ARGV[0], "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

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

get=data.sort[0, m].select{|v| v<0}.inject(0){|sum, val| sum+=val}.abs
puts get

# coding: utf-8

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
earned = 0
a[0...m].each { |i|
    earned += -i if i < 0
}
puts earned

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i).select{|a| a<0}.sort[0..(m-1)]
sum = arr.inject(0,:+)
puts -sum

m, n = gets.split.map!(&:to_i)
a = gets.split.map!(&:to_i).select{|e| e <= 0}.sort!.first(n).inject(0) {|res, elem| res + elem}
puts a.abs

n, m = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.select{|i| i<0}.sort
if a.size == 0
    puts 0
    exit
end
puts a[0,m].inject{|sum,i| sum+=i}.abs
'''
if m > a.size
    puts a.inject{|sum,i| sum+=i}.abs
else
    puts a[0,m].inject{|sum,i| sum+=i}.abs
end
'''

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

min, sum = 0, 0

prices.sort[0..m - 1].each do |p|
  sum += p
  min = [min, sum].min
end

puts min.abs

n, m = gets.strip.split(" ").map{|s| s.to_i}
prices = gets.strip.split(" ").map {|s| - s.to_i}.reject {|j| j <= 0}.sort.reverse
print prices[0...m].reduce(0, :+)

n, m = gets.split.map{|s| s.to_i}
prices = gets.split.map {|s| s.to_i}.select {|j| j < 0}.sort
print -prices[0...m].reduce(0, :+)

n, m = gets.split(' ').map(&:to_i)
puts gets.split(' ').map(&:to_i).select { |x| x < 0 }.sort.first(m).inject(0, &:+).abs

a = gets.chop.split(/ /)
a.map! do |i|
i = i.to_i
end

b = gets.chop.split(/ /)
b.map! do |i|
i = i.to_i
end

$cnt=0
$tmp = Array.new
for i in 0..(b.size-1)
if b[i] < 0
$tmp[$cnt] = i
$cnt=$cnt + 1
end
end

$sum = 0
if $cnt <= a[1]
$tmp.each do |i|
$sum=$sum - b[i]
end
else
b.sort!
for i in 0..a[1]
$sum=$sum - b[i]
end
end

puts $sum

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i).sort
t,i=0,0
while n!=0
	t+=a[i] if a[i]<0
	n-=1
	i+=1
end
puts -t

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).find_all {|x| x < 0 }
puts (sc = a.first([a.size, m].min).inject(:+)).nil? ? 0 : -sc

n, m = gets.split.map(&:to_i)
j, score = 0, 0
a = gets.split.map(&:to_i).sort!
while j<=m and a[j] < 0
  score += a[j]
  j+=1
end
puts -score

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}.sort
ans=0
m.times{|i|
	ans-=x[i]
}
puts ans

#=================================
if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open(ARGV[0], "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

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

get=data.select{|v| v<0}.inject(0){|sum, val| sum+=val}.abs
puts get

# coding: utf-8

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
puts -a[0...m].reduce(:+)

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i).select{|a| a<0}.sort
sum = arr.inject(0,:+)
puts -sum

n, m = gets.chomp.split.map(&:to_i)
puts gets.chomp.split.map(&:to_i).sort[0..m - 1].inject(0) { |sum, v| sum + v }.abs

n, m = gets.strip.split(" ").map{|s| s.to_i}
prices = gets.strip.split(" ").map {|s| - s.to_i}.reject {|j| j <= 0}.sort.reverse
m = prices.length if m > prices.length
print prices[0..m].reduce(0) {|s, a| s + a}


You have a large electronic screen which can display up to $$$998244353$$$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $$$7$$$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $$$10$$$ decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $$$1$$$, you have to turn on $$$2$$$ segments of the screen, and if you want to display $$$8$$$, all $$$7$$$ segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $$$n$$$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $$$n$$$ segments.Your program should be able to process $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$.

For each test case, print the greatest integer that can be displayed by turning on no more than $$$n$$$ segments of the screen. Note that the answer may not fit in the standard $$$32$$$-bit or $$$64$$$-bit integral data type.

gets.strip.to_i.times do
  n = gets.strip.to_i
  if n % 2 == 0
    puts "1" * (n / 2)
  else
    puts "7" + ("1" * ((n - 3) / 2))
  end
end

T = gets.to_i

T.times do
  n = gets.to_i

  if n % 2 == 0
    puts '1' * (n / 2)
  else
    puts '7' + '1' * ((n - 3) / 2)
  end
end

T = gets.to_i

T.times do
  n = gets.to_i

  if n % 2 == 0
    puts '1' * (n / 2)
  else
    puts '1' * ((n - 3) / 2) + '7'
  end
end


You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 990$$$) — the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \le n \le 999$$$).

For each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.

NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers — $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$.

n = gets.chomp.to_i
for _ in 0...n
  num = gets.chomp
  len = num.length()
  if num.to_i % 7 == 0
    puts num
  else
    for i in 1..9
      temp = (num[0, len-1] + i.to_s).to_i
      if temp % 7 == 0
        puts temp
        break
      end
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  if n % 7 == 0
    puts n
  else
    m = n / 10
    (0..9).each { |d|
      if (m - 2 * d) % 7 == 0
        puts "#{m}#{d}"
        break
      end
    }
  end
end


You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \le a_i + a_j \le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable:   $$$i=1$$$ and $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$);  $$$i=1$$$ and $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \le a_i + a_j \le r$$$.

def l_bound(x, i, a)
  lo, hi = 0, i - 1
  while lo <= hi
    mi = (lo + hi) / 2
    if a[mi] < x
      lo = mi + 1
    elsif
      hi = mi - 1
    end
  end
  return lo
end

def u_bound(x, i, a)
  lo, hi = 0, i - 1
  while lo <= hi
    mi = (lo + hi) / 2
    if a[mi] <= x
      lo = mi + 1
    elsif
      hi = mi - 1
    end
  end
  return hi
end

for t in 0...gets.to_i
  n, l, r = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i).sort
  ans = 0
  (0...n).each do |i|
    lo = l_bound(l - a[i], i, a)
    hi = u_bound(r - a[i], i, a)
    if lo <= hi and lo >= 0 and hi < i
      ans += hi - lo + 1
    end
  end
  puts ans
end

gets.to_i.times do
  n,l,r=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i).sort
  c=0
  i=0
  j=n-1
  k=n-1
  while i<n
    while j>i&&a[i]+a[j]>=l
      j-=1
    end
    while k>0&&a[i]+a[k]>r
      k-=1
    end
    c+=[k,i].max-[j,i].max
    i+=1
  end
  puts c
end


Let $$$f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$$$ for $$$x \ge 4$$$.You have given integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$. Find $$$f_{n} \bmod (10^{9}+7)$$$.

require 'Matrix'

def modpowMatrix(x,n)
  ret = Matrix.I(x.column_size)
  while n > 0
    ret = (ret * x).map{|v| v % (MOD-1)} if n&1 == 1
    x = (x*x).map{|v| v % (MOD-1)}
    n >>= 1
  end
  return ret
end

def modpow(x,n)
  ret = 1
  while n > 0
    ret = (ret * x) % MOD if n&1 == 1
    x = (x*x) % MOD
    n >>= 1
  end
  return ret
end

MOD = 10**9+7
n,x,y,z,c = gets.split.map(&:to_i)
a = Matrix.rows([[1,1,1],[1,0,0],[0,1,0]])
b = Matrix.rows([[1,1,1,1,0],[1,0,0,0,0],[0,1,0,0,0],[0,0,0,1,1],[0,0,0,0,1]])

m = modpowMatrix(a,n-3)
ft = Matrix.columns([[0,0,0,2,2]])
k = (modpowMatrix(b,n-3)*ft)[0,0] % (MOD-1)
p ((modpow(c,k) * modpow(z,m[0,0]) % MOD) * modpow(y,m[0,1]) % MOD) * modpow(x,m[0,2]) % MOD

require 'Matrix'

def modpowMatrix(x,n)
  ret = Matrix.I(x.column_size)
  while n > 0
		ret = (ret * x).map{|v| v%MOD} if n&1 == 1
    x = (x*x).map{|v| v%MOD}
    n >>= 1
  end
  return ret
end

def modpow(x,n)
  ret = 1
  while n > 0
    ret = (ret * x) % MOD if n&1 == 1
    x = (x*x) % MOD
    n >>= 1
  end
  return ret
end

MOD = 10**9+7
n,x,y,z,c = gets.split.map(&:to_i)
a = Matrix.rows([[1,1,1],[1,0,0],[0,1,0]])
b = Matrix.rows([[1,1,1,1,0],[1,0,0,0,0],[0,1,0,0,0],[0,0,0,1,1],[0,0,0,0,1]])

m = modpowMatrix(a,n-3)
cf = Matrix.columns([[0,0,0,2,2]])
k = (modpowMatrix(b,n-3)*cf)[0,0] % MOD
p ((modpow(c,k) * modpow(z,m[0,0]) % MOD) * modpow(y,m[0,1]) % MOD) * modpow(x,m[0,2]) % MOD


Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.

The first line contains integer n (3 ≤ n ≤ 100) — amount of worm's forms. The second line contains n space-separated integers ai (1 ≤ ai ≤ 1000) — lengths of worms of each form.

Output 3 distinct integers i j k (1 ≤ i, j, k ≤ n) — such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.

n = gets.to_i

lens = gets.split.map{|i| i.to_i}

i = 0
k = true
while k && i < n-1 do
    j = 1
    while k && j < n do
        if (t = lens.index(lens[i] + lens[j])) then
            k = false
            result = (t+1).to_s + " " + (i+1).to_s + " " + (j+1).to_s
        end
        j += 1
    end
    i += 1
end

if k then
    puts "-1"
else
    puts result
end

@ok = false

def chk3(arr, i, j, k)
	if (arr[i] == arr[j]+arr[k])
		puts (i+1).to_s + " " + (j+1).to_s + " " + (k+1).to_s
		@ok = true
		return true
	end
	return false
end

n = gets.to_i
s = gets
na = s.split(/ /)
arr = Array.new(n)
for i in 0..n-1
  arr[i] = na[i].to_i
end

(n-1).downto(2) { |i|
	(i-1).downto(1) { |j|
		(j-1).downto(0) { |k|
			break if chk3(arr, i, j, k)
			break if chk3(arr, i, k, j)
			break if chk3(arr, j, i, k)
			break if chk3(arr, j, k, i)
			break if chk3(arr, k, i, j)
			break if chk3(arr, k, j, i)
		}
		break if @ok
	}
	break if @ok
}
puts("-1") if @ok == false

#!/usr/bin/ruby
gets;a=gets.split.map(&:to_i)
a.size.times{|i|a.size.times{|j|(j+1).step(a.size-1){|k|
	if a[i]==a[j]+a[k] then puts [i+1,j+1,k+1]*' ';exit end
}}}
p -1

n=gets.to_i
a=[0]+gets.split.map(&:to_i)
1.upto(n).to_a.combination(2).each{|i,j|k=a.index a[i]+a[j];"#{p k,i,j;exit}"if k}
p -1

a = gets.chop

b = gets.chop.split(/ /)
b.map! do |i|
i = i.to_i
end

c = Array.new
flag = 0
for i in 0..b.size-1
	for j in i+1..b.size-1
		for k in j+1..b.size-1
			if b[i] == b[j]+b[k]
				flag=1
				c[0]=i+1
				c[1]=j+1
				c[2]=k+1
			elsif b[j] == b[i]+b[k]
				flag=1
				c[0]=j+1
				c[1]=i+1
				c[2]=k+1
			elsif b[k] == b[i]+b[j]
				flag=1
				c[0]=k+1
				c[1]=i+1
				c[2]=j+1
			end
			if flag==1
				break
			end
		end
		if flag==1
			break
		end
	end
	if flag==1
		break
	end
end

if flag==0
	print -1
else
	for i in 0..c.size-1
		print c[i]
		if i !=c.size-1
			print " "
		end
	end
end

a = gets.chop

b = gets.chop.split(/ /)
b.map! do |i|
i = i.to_i
end

c = Array.new
flag = 0
for i in 0..b.size-1
	for j in i+1..b.size-1
		for k in j+1..b.size-1
			if b[i] == b[j]+b[k]
				flag=1
				c[0]=i+1
				c[1]=j+1
				c[2]=k+1
			elsif b[j] == b[i]+b[k]
				flag=1
				c[0]=j+1
				c[1]=i+1
				c[2]=k+1
			elsif b[k] == b[i]+b[j]
				flag=1
				c[0]=k+1
				c[1]=i+1
				c[2]=j+1
			end
			if flag==1
				break
			end
		end
		if flag==1
			break
		end
	end
	if flag==1
		break
	end
end

if flag==0
	print -1
else
	for i in 0..c.size-1
		print c[i].to_s + " "
	end
end

n=gets.to_i
a=gets.chomp.split.map(&:to_i)
for i in 0...n
	for j in 0...n
		for k in 0...n
			if i!=j && i!=k && j!=k && a[i]==a[j]+a[k]
				puts "#{i+1} #{j+1} #{k+1}"
				exit
			end
		end
	end
end
puts "-1"

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
done = false
x = y = z = 0
n.times do |i|
    break if done
    ai = a[i]
    n.times do |j|
        next if i == j
        break if done
        aj = a[j]
        n.times do |k|
            next if j == k
            if aj + a[k] == ai
                x = i + 1
                y = k + 1
                z = j + 1
                done = true
                break
            end
        end
    end
end
if !done
    puts "-1"
else
    puts "#{x} #{y} #{z}"
end

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

q = {}
a.each_index { |i| q[a[i]] = i }

n.times do |i|
    i.times do |j|
        if q[ a[i] + a[j] ] != nil
            puts "#{ q[a[i] + a[j]] + 1 } #{i + 1} #{j + 1}"
            exit
        end
    end
end

puts "-1"

def main()
	n=gets.chomp.to_i
	strinp=gets.chomp.split(" ")
	strinp=strinp.map{|i| i.to_i}
	for i in 0...n
		sum=strinp[i]
		f=false
		for j in 0...n
			rem=sum-strinp[j]
				for k in 0...n
					if strinp[k]==rem && k!=j && k!=i
						puts "%d %d %d" %[i+1,j+1,k+1]
						f=true
						break
					end
				end
			if f
				break
			end
		end
		if f
			break
		end
	end
	if !f
		puts "-1"
	end
end
main()

# def bin_search(arr,e)
# 	n = arr.length
# 	l = 0
# 	r = n - 1

# 	while l <= r
# 		m = l + (r-l) / 2
# 		if arr[m] == e
# 			puts "#{m}"
# 			return m
# 		elsif e < arr[m]
# 			r = m - 1
# 		else
# 			l = m + 1
# 		end
# 	end

# 	return false

# end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
# arr.sort!
ans = false
ans_i = ans_j = ans_k = 0
arr.each_with_index do |i,ind_i|
	arr[ind_i+1..-1].each_with_index do |j,ind_j|
		# puts "#{i+j} ans #{bin_search(arr[ind_j+1..-1], i + j)}"
		ind_k = arr.index(i+j) #bin_search(arr[ind_j+1..-1], i + j)
		# puts "#{i} #{j} #{ind_k}"
		if ind_k
			ans = true
			ans_j = ind_i
			ans_k = ind_i + ind_j + 1
			ans_i = ind_k
			break
		end
	end
	break if ans
end

puts ans ? "#{ans_i+1} #{ans_j+1} #{ans_k+1}": "-1"

gets
mas = gets.split(" ")
for i in (0..mas.size - 1)
  mas[i] = mas[i].to_i
end

for i in (0..mas.size - 1)
  for j in (0..mas.size - 1)
    for k in (0..mas.size - 1)
      if (i != j && j != k && i != k && mas[i] == mas[j]+mas[k])
        print i+1, " ", j+1, " ", k+1
        exit
      end
    end
  end
end

print -1

gets
worms = gets.chomp.split.map(&:to_i)

res = [-1]
found = false
worms.each_with_index do |w1, i|
  break if found
  worms.each_with_index do |w2, j|
    break if found
    next if j == i
    worms.each_with_index do |w3, k|
      break if found
      next if k == j or k == i
      if w3 == w1 + w2
        res = [k.succ, j.succ, i.succ]
        found = true
      end
    end
  end
end
puts res.join(' ')

n = gets.to_i

lens = gets.split.map{|i| i.to_i}

i = 0
k = true
while k && i < n-1 do
    j = 1
    while k && j < n do
        if (t = lens.index(lens[i] + lens[j])) then
            k = false
            result = lens[t].to_s + " " + lens[i].to_s + " " + lens[j].to_s
        end
        j += 1
    end
    i += 1
end

if k then
    puts "-1"
else
    puts result
end

n = gets.to_i
s = gets
na = s.split(/ /)
arr = Array.new(n)
for i in 0..n-1
  arr[i] = na[i].to_i
end
arr.sort!
ok = false
(n-1).downto(2) { |i|
	(i-1).downto(1) { |j|
		(j-1).downto(0) { |k|
			if (arr[i] == arr[j]+arr[k])
				puts (i+1).to_s + " " + (j+1).to_s + " " + (k+1).to_s
				ok = true
				break
			end
		}
		break if ok
	}
	break if ok
}
puts("-1") if ok == false

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
done = false
x = y = z = 0
n.times do |i|
    break if done
    ai = a[i]
    (1...n).each do |j|
        if a[j - 1] + a[j] == ai
            x = i + 1
            y = j + 1
            z = j
            done = true
            break
        end
    end
end
if !done
    puts "-1"
else
    puts "#{x} #{y} #{z}"
end

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
done = false
x = y = z = 0
n.times do |i|
    break if done
    ai = a[i]
    n.times do |j|
        break if done
        aj = a[j]
        n.times do |k|
            if aj + a[k] == ai
                x = i + 1
                y = j + 1
                z = k + 1
                done = true
                break
            end
        end
    end
end
if !done
    puts "-1"
else
    puts "#{x} #{y} #{z}"
end

gets
a=gets.split.map &:to_i
a.combination(2).each{|i,j|"#{p i+j,i,j;exit}"if a.index i+j}
p -1

def main()
	n=gets.chomp.to_i
	strinp=gets.chomp.split(" ")
	strinp=strinp.map{|i| i.to_i}
	for i in 0...n
		sum=strinp[i]
		f=false
		for j in 0...n
			rem=sum-strinp[j]
			search=strinp-[sum,strinp[j]]
			if search.include?(rem)
				puts "%d %d %d" %[sum,strinp[j],rem]
				f=true
				break
			end
		end
		if f
			break
		end
	end
	if !f
		puts "-1"
	end
end
main()

# def bin_search(arr,e)
# 	n = arr.length
# 	l = 0
# 	r = n - 1

# 	while l <= r
# 		m = l + (r-l) / 2
# 		if arr[m] == e
# 			puts "#{m}"
# 			return m
# 		elsif e < arr[m]
# 			r = m - 1
# 		else
# 			l = m + 1
# 		end
# 	end

# 	return false

# end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
# arr.sort!
ans = false
ans_i = ans_j = ans_k = 0
arr.each_with_index do |i,ind_i|
	arr[ind_i+1..-1].each_with_index do |j,ind_j|
		# puts "#{i+j} ans #{bin_search(arr[ind_j+1..-1], i + j)}"
		ind_k = arr[ind_j+1..-1].index(i+j) #bin_search(arr[ind_j+1..-1], i + j)
		# puts "#{i} #{j} #{ind_k}"
		if ind_k
			ans = true
			ans_j = ind_i
			ans_k = ind_i + ind_j + 1
			ans_i = ans_k + ind_k
			break
		end
	end
	break if ans
end

puts ans ? "#{ans_i+1} #{ans_j+1} #{ans_k+1}": "-1"

def bin_search(arr,e)
	n = arr.length
	l = 0
	r = n - 1

	while l <= r
		m = l + (r-l) / 2
		if arr[m] == e
			return true
		elsif e < arr[m]
			r = m - 1
		else
			l = m + 1
		end
	end

	return false

end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
arr.sort!
ans = false
ans_i = ans_j = ans_k = 0
arr.each_with_index do |i,ind_i|
	arr[ind_i+1..-1].each_with_index do |j,ind_j|
		# puts "#{i+j} ans #{bin_search(arr[ind_j+1..-1], i + j)}"
		if bin_search(arr[ind_j+1..-1], i + j)
			ans = true
			ans_i = i + j
			ans_j = i
			ans_k = j
			break
		end
	end
	break if ans
end

puts ans ? "#{ans_i} #{ans_j} #{ans_k}": "-1"

gets
worms = gets.chomp.split.map(&:to_i)

res = [-1]
found = false
worms.each_with_index do |w1, i|
  break if found
  worms.each_with_index do |w2, j|
    break if found
    next if j == i
    worms.each_with_index do |w3, k|
      break if found
      next if k == j or k == i
      if w3 == w1 + w2
        res = [i.succ, j.succ, k.succ]
        found = true
      end
    end
  end
end
puts res.join(' ')


There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, all $$$f_i \ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.

Print $$$n$$$ integers $$$nf_1, nf_2, \dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.

require 'set'

n = readline.to_i
f = [nil] + readline.split.map(&:to_i)

zeros = (1..n).select { |i| f[i] == 0 }.to_set
sources = (1..n).select { |i| f[i] != 0 and f[f[i]] == 0 }
sinks = (1..n).to_set.difference(f).select { |i| f[i] != 0 }

if sources.length > 1 then
  for source in sources[0..-2] do
    f[f[source]] = sinks.pop
    zeros.delete(f[source])
  end
end

zeros = zeros.to_a
zeros.each_cons(2) do |i,j|
  f[i] = j
end
f[zeros[-1]] = zeros[0]

if sources.length > 0 then
  if zeros.length > 1 then
    f[zeros[(zeros.find_index(f[sources[-1]]) - 1) % zeros.length]] = sinks.pop
  else
    f[f[sources[-1]]] = sinks.pop
  end
end

print(f[1..-1].join(' '))

gets.strip.to_i
f = gets.strip.split(' ').map(&:to_i)
no_rece = Array.new(f.size, -1)
no_give = []
f.each_with_index do |e, i|
  no_give << (i+1) if e.zero?
  no_rece[e - 1] = i unless e.zero?
end
no_rece = no_rece.each_with_index.map { |e, i| e == -1 ? (i + 1) : nil }.compact.sort
no_give = no_give.sort.reverse
# inter = no_rece & no_give
# puts no_rece.inspect
# puts no_give.inspect
no_give.each_with_index do |e, i|
  if no_rece[i] == e
    a = no_give[i]
    b = no_rece[i]
    c = i ==0 ? no_give[i +1] : no_give[i - 1]
    d = i ==0 ? no_rece[i +1] : no_rece[i - 1]
    # no_give[i] = c
    # no_give[i == 0 ? i + 1 : i - 1] = a
    no_rece[i] = d
    no_rece[i == 0 ? i + 1 : i - 1] = b
  end
end
# puts no_rece.inspect
# puts no_give.inspect
no_give.each_with_index do |e, i|
  f[e - 1] = no_rece[i]
end
puts f.join(" ")
# puts f.map { |e| e.zero? ?  }

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

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

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi
f=gsmi
fixed=f.sort_by{|x|-x}.to_a
#puts f.to_s
#puts fixed.to_s

ar=(1..n).to_a
pos=[]
n.times do |i|
  if f[i]==0
    pos<<i+1
    next
  end
end
n.times do |i|
  break if fixed[i]==0
  ar.delete_at(fixed[i]-1)
end
#puts ar.to_s
lackpos = ar & pos
ar3 = ar - lackpos
# puts ar.to_s
# puts pos.to_s
# puts lackpos.to_s
# puts ar3.to_s
if lackpos.size==1
  f[lackpos[0]-1]=ar3[0]
  ar3[0]=lackpos[0]
elsif lackpos.size>0
  s=lackpos.size
  s.times do |i|
    f[lackpos[i]-1]=lackpos[(i+1)%s]
  end
end
#puts f.to_s

n.times do |i|
  next if f[i]!=0
  f[i]=ar3.shift

  break if ar.size==0
end

puts f.join(" ")

n=gets.to_i
f=gets.split.map(&:to_i)
fixed=f.sort_by{|x|-x}.to_a
#puts f.to_s
#puts fixed.to_s

ar=(1..n).to_a
n.times do |i|
    break if fixed[i]==0
    ar.delete_at(fixed[i]-1)
end
#puts ar.to_s
ar.push(ar.shift)
n.times do |i|
    next if f[i]!=0
    nn=ar.shift
    if nn==i+1
        f[i]=ar.shift
        ar<<nn
    else
      f[i]=nn
    end
    break if ar.size==0
end

puts f.join(" ")

n=gets.to_i
f=gets.split.map(&:to_i)
fixed=f.sort_by{|x|-x}.to_a
#puts f.to_s
#puts fixed.to_s

ar=(1..n).to_a
n.times do |i|
    break if fixed[i]==0
    ar.delete_at(fixed[i]-1)
end
#puts ar.to_s
ar.push(ar.shift) if ar[0]==f.index(0)
n.times do |i|
    next if f[i]!=0
    nn=ar.shift
    if nn==i+1
        f[i]=ar.shift
        ar<<nn
    else
      f[i]=nn
    end
    break if ar.size==0
end

puts f.join(" ")


zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!

The only line contains the string s (1 ≤ |s| ≤ 2·105) — the string given to zscoder. The string s consists of only lowercase English letters.

Print the simple string s' — the string s after the minimal number of changes. If there are multiple solutions, you may output any of them. Note that the string s' should also consist of only lowercase English letters.

def getNextChar(c)
  return 'a' if c == 'z'
  return c.next
end
string = gets.chomp
for i in 0..string.length - 2 do
  while string[i] == string[i + 1]
    if i < string.length - 2
      while string[i] == string[i + 1] or string[i+1] == string[i+2]
        string[i+1] = getNextChar(string[i+1])
      end
    else
      while string[i + 1] == string[i]
        string[i+1] = getNextChar(string[i+1])
      end
    end
  end
end
puts string

arr = readline.strip.each_char.to_a
1.upto(arr.length - 1) do |ind|
  if arr[ind] == arr[ind - 1]
    arr[ind] = 'd'
    if arr[ind] == arr[ind - 1] ||
        (ind < arr.length - 1 && arr[ind] == arr[ind + 1])
      arr[ind] = 'q'
    end
    if arr[ind] == arr[ind - 1] ||
        (ind < arr.length - 1 && arr[ind] == arr[ind + 1])
      arr[ind] = 'c'
    end
  end
end
puts arr.join