def insertionSort( nums, n, g )
	cnt = 0
	for i in ( g ... nums.length )
	    v = nums[i]
	    j = i - g
	    while 0 <= j && v < nums[j]
	        nums[ j+g ] = nums[j]
	        j -= g
	        cnt += 1
	    end
	    nums[ j+g ] = v
	end

	return cnt
end

def shellSort( nums, n )
	cnt = 0
	g = []
	for i in ( 0 ... n )
		val = 3*i+1
		break if  n < val
		g.push( val )
	end
	g.reverse!
	m = g.length
	puts( m )
	puts( g.join( " " ) )
	for i in ( 0 ... m )
		cnt += insertionSort( nums, n, g[i] )
	end
    puts( cnt )
end

n = gets.to_i
nums = []
for i in ( 0 ... n )
	nums.push( gets.to_i )
end

shellSort( nums, n )
nums.each { |val| puts( val ) }

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Shell Sort

Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])

A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.

Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:

$1 \leq m \leq 100$

$0 \leq G_i \leq n$

cnt does not exceed $\lceil n^{1.5}\rceil$

Input

In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.

Output

In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.

In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints

$1 \leq n \leq 1,000,000$

$0 \leq A_i \leq 10^9$

Sample Input 1

5
5
1
4
3
2

Sample Output 1

2
4 1
3
1
2
3
4
5

Sample Input 2

3
3
2
1

Sample Output 2

1
1
3
1
2
3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


def insertionSort(a,n,g)
  cnt = 0
  for i in g..n-1
    v = a[i]
    j = i-g
    while j>=0 && a[j]>v do
      a[j+g] = a[j]
      j = j-g
      cnt += 1
    end
    a[j+g] = v
  end
  return cnt
end

def makeShellNum(n)
  num = 0
  arr = []
  tmp = 1
  while n >= tmp do
    arr << tmp
    num += 1
    tmp = 3*tmp + 1
  end
  return num,arr.reverse
end

def shellSort(a,n)
  cnt = 0
  m,g = makeShellNum(n)
  for i in 0..m-1
    cnt += insertionSort(a,n,g[i])
  end
  printf("%d\n%s\n%d\n%s\n",m,g.join(" "),cnt,a.join("\n"))
end

n = gets.chomp.to_i
a = []
for i in 1..n do
  a[i-1] = gets.chomp.to_i
end
shellSort(a,n)


def insertion_sort(array, n, g)
  cnt = 0
  g.upto n - 1 do |i|
    v = array[i]
    j = i - g
    while j >= 0 && array[j] > v
      array[j + g] = array[j]
      j -= g
      cnt += 1
    end
    array[j + g] = v
  end
  cnt
end

def shell_sort(array, n)
  cnt = 0
  g = [1]
  g << 3 * g[-1] + 1 until 3 * g[-1] + 1 > n
  m = g.length
  g.reverse_each do |value|
    cnt += insertion_sort(array, n, value)
  end
  [array, cnt, m, g]
end

n = gets.to_i
array = []
n.times do
  array << gets.to_i
end

result = shell_sort array, n

puts result[2]
puts result[3].join(' ')
puts result[1]
puts result[0]


class Dic
  def initialize
    @aword = [" "]
    @cword = [" "]
    @gword = [" "]
    @tword = [" "]
  end

  def insert(str)
    case str.split(//)[0]
    when "A"
      @aword << str
    when "C"
      @cword << str
    when "G"
      @gword << str
    when "T"
      @tword << str
    end
  end

  def find(str)
    case str.split(//)[0]
    when "A"
      @aword.sort!
      words = @aword
    when "C"
      @cword.sort!
      words = @cword
    when "G"
      @gword.sort!
      words = @gword
    when "T"
      @tword.sort!
      words = @tword
    end
    if include?(words, str)
      puts 'yes'
    else
      puts 'no'
    end
  end

  def include?(arr, n)
    if arr.length == 1
      return arr[0] == n
    else
      if arr[arr.length / 2] <= n
        return include?(arr[arr.length / 2..arr.length - 1], n)
      else
        return include?(arr[0...arr.length / 2], n)
      end
    end
  end
end
dic = Dic.new
gets.to_i.times do
  dic.send(*gets.split(" "))
end

Search III

Your task is to write a program of a simple dictionary which implements the following instructions:

insert str: insert a string str in to the dictionary

find str: if the distionary contains str, then print 'yes', otherwise print 'no'

Input

In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.

Output

Print yes or no for each find instruction in a line.

Constraints

A string consists of 'A', 'C', 'G', or 'T'

1 ≤ length of a string ≤ 12

n ≤ 1000000

Sample Input 1

5
insert A
insert T
insert C
find G
find A

Sample Output 1

no
yes

Sample Input 2

13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T

Sample Output 2

yes
no
no
yes
yes
yes

Notes

Template in C


class Dic
  def initialize
    @word = [" "]
    @queue = []
  end

  def insert(str,i)
    @word << [str,i]
  end

  def find(str,i)
    @queue << [str,i]
  end

  def uniq
    @word = @word.uniq{|item|item[0]}.sort_by{|item|item[0]}
  end

  def exe
    uniq
    @queue.each do |str|
      if include?(@word, str)
        puts 'yes'
      else
        puts 'no'
      end
    end
  end

  def include?(arr, n)
    if arr.length == 1
      return ((arr[0][0] == n[0]) and (arr[0][1] < n[1]))
    else
      if arr[arr.length / 2][0] <= n[0]
        return include?(arr[arr.length / 2..arr.length - 1], n)
      else
        return include?(arr[0...arr.length / 2], n)
      end
    end
  end
end
def testf
  test = open("dic2.txt")
  dic = Dic.new
  i = 0
  test.gets
  while str = test.gets
    dic.send(*str.split(" "), i)
    i += 1
  end
  dic.exe
end
def f
  dic = Dic.new
  i = 0
  gets.to_i.times do
    dic.send(*gets.split(" "),i)
    i += 1
    if i % 100000 == 0
      dic.uniq
    end
  end
  dic.exe
end
f


class Dictionary

	def initialize
		@table = []
	end

	def insert(e)
		i = 0
		loop do
			key = (hashcode(e) + i * hashcode2(e)) % SEED
			unless @table[key]
				@table[key] = e
				return self
			end
			i += 1
		end
	end

	def find(e)
		i = 0
		loop do
			key = (hashcode(e) + i * hashcode2(e)) % SEED
			if !@table[key]
				return false
			elsif @table[key] == e
				return true
			end
			i += 1
		end
	end

	private
	SEED = 16777219

	def hashcode(e)
		n = e.sum
		n % SEED
	end

	def hashcode2(e)
		n = e.sum
		1 + (n % (SEED - 1))
	end

end

n = STDIN.gets.to_i
dictionary = Dictionary.new
n.times do
	operation, parameter = STDIN.gets.split
	if operation == "insert"
		dictionary.send(operation, parameter)
	elsif operation == "find"
		found = dictionary.send(operation, parameter)
		puts(found ? "yes" : "no")
	else
		raise "Invalid input: #{operation}, #{parameter}"
	end
end


def h(key)
  key.hash % 65535
end

class Dict
  def initialize
    @arr = []
  end
  def insert(s)
    @arr[h(s)] = s
  end
  def find(s)
    @arr[h(s)]
  end
end

n = STDIN.gets.to_i

dict = Dict.new
n.times.each {
  ss = STDIN.gets.split(' ')
  if ss[0] == 'insert' then
    dict.insert(ss[1])
  else
    if dict.find(ss[1]) then
      puts 'yes'
    else
      puts 'no'
    end
  end
}


class Node
  def initilize
    @act = false
  end

  def insert(val)
    if val.empty?
      @act=true
    else
      case val[0]
      when 'A'
        @a = Node.new if @a.nil?
        @a.insert(val[1..-1])
      when 'C'
        @c = Node.new if @c.nil?
        @c.insert(val[1..-1])
      when 'G'
        @g = Node.new if @g.nil?
        @g.insert(val[1..-1])
      when 'T'
        @t = Node.new if @t.nil?
        @t.insert(val[1..-1])
      end
    end
  end

  def find(val)
    if val.empty?
      return @act
    else
      case val[0]
      when 'A'
        @a and @a.find(val[1..-1])
      when 'C'
        @c and @c.find(val[1..-1])
      when 'G'
        @g and @g.find(val[1..-1])
      when 'T'
        @t and @t.find(val[1..-1])
      end
    end
  end

  def dump
    p "@act: #{@act}, a:#{@a}, c:#{@c}, g:#{@g}, t:#{@t}"
  end
end

num = STDIN.gets
commands = STDIN.read.split("\n")

root = Node.new
commands.each do |command|
  proc,arg = command.split(' ')
  # p "command: #{proc} #{arg}"
  case proc
  when 'insert'
    root.insert(arg)
  when 'find'
    if root.find(arg)
      print "yes\n"
    else
      print "no\n"
    end
  end
end


n = gets.to_i
list = []

n.times do
  cmd, str = gets.split
  case cmd
  when "insert"
    list.unshift(str)
  when "find"
    index = list.find_index { |i| i == str }
    unless index.nil?
      puts "yes"
    else
      puts "no"
    end
  end
end


def dictionary(orders)
  str = ""
  length = orders.length
  for i in 0..(length-1)
    if orders[i][0] == "insert"
      str += orders[i][1]
    elsif orders[i][0] == "find"
      if str.index(orders[i][1]) == nil
        puts "no"
      else
        puts "yes"
      end
    else
      puts "error!"
    end
  end
end

n = gets.chomp.to_i
orders = []
n.times do
  order = gets.chomp.split
  orders.push(order)
end
dictionary(orders)


def add word
	val = hashFunc word
    val = (val + 1) % @dic.length while @dic[val]
    @dic[val] = word
end

def hashFunc word
	word.gsub!("A", "1")
	word.gsub!("C", "2")
	word.gsub!("G", "3")
	word.gsub!("T", "4")
    val = word.to_i % @dic.length
end

def find word
	val = hashFunc word
	while true
        return true if @dic[val] == word
        return false unless @dic[val]
        val = (val + 1) % @dic.length
    end
end

@dic = Array.new(4 ** 12)

n = gets.to_i
n.times{
	command, word = gets.chomp.split
	case command
	when "insert"
		add word
	else
		puts (find word) ? "yes" : "no"
	end
}


def add word
	h1, h2 = getHashV word
	h = h1
	i = 0
	while @dic[h]
		i += 1
		h = (h1 + h2 * i) % @dic.length
	end
	@dic[h] = word
end

def find word
	h1, h2 = getHashV word
	h = h1
	i = 0
	while true
		return true if @dic[h] == word
		return false unless @dic[h]
		i += 1
		h = (h1 + h2 * i) % @dic.length
	end
end

def getHashV word
	num = toN word
	[hashF1(num), hashF2(num)]
end

def hashF1 num
	num % @dic.length
end

def hashF2 num
	num % (@dic.length - 1) + 1
end

def toN word
	num = word.dup
	num.gsub!("A", "1")
	num.gsub!("C", "2")
	num.gsub!("G", "3")
	num.gsub!("T", "4")
	num.to_i
end

n = gets.to_i
@dic = Array.new(1999993)
n.times{
	command, word = gets.chomp.split
	case command
	when "insert"
		add word
	else
		puts (find word) ? "yes" : "no"
	end
}


#!/usr/bin/env ruby

n = gets.chomp.to_i

dict = {}
n.times do
  action, str = gets.chomp.split

  case action
  when 'insert'
    dict[str.to_sym] = 1
  when 'find'
    puts dict[str.to_sym] ? 'yes' : 'no'
  end
end


_, *orders = readlines.map(&:chomp)
orders = orders.map(&:split)
dictionary = {}
orders.each do |o, s|
  if o == 'insert'
    dictionary[s] = dictionary.size + 1
  else
    puts dictionary[s] ? 'yes' : 'no'
  end
end


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

i = 0
sum = 0
each_sum = 0
while i < n-1
  each_sum += arr[i]
  sum += arr[i] * (arr.sum - each_sum)
  # a*b+ a*c + a*d + b*c + b*d + c*d
  # a(b+c+d) + b(c+d) +
  #
  #
  i += 1
end
puts sum%mod

Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

2 \leq N \leq 2\times 10^5

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829


n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
bigmod = 10 ** 9 + 7
sum = arr[0] + arr[1]
mod = arr[0] * arr[1]
2.upto(arr.length-1) do |i|
	mod += sum * arr[i]
	mod %= bigmod
	sum += arr[i]
end

puts mod


mod = 1_000_000_007

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

tmp0 = a.sum
tmp0 = ((tmp0 % mod) ** 2) % mod

tmp1 = a.sum { |e|
  e ** 2
}

tmp1 %= mod

puts tmp0 < tmp1 ? (tmp0 - tmp1 + mod) / 2 : (tmp0 - tmp1) / 2


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

arr.permutation(2).to_a.map { |a| a.sort }.uniq.each { |i, j| sum = sum + (i*j) }

puts sum


input = readlines()
n = input.shift.chomp.to_i
list = input.shift.chomp.split("\s").map{|x| x.to_i}

res = 0
list.each_with_index do |l1, i1|
  list.each_with_index do |l2, i2|
    next if i1 >= i2
    res += l1 * l2

    if res > 1000000007
      res = res % 1000000007
    end

  end
end

puts res


class InputLine
  def self.to_s
    gets.chomp
  end

  def self.to_i
    InputLine.to_s.to_i
  end

  def self.to_f
    InputLine.to_s.to_f
  end

  def self.to_sa
    InputLine.to_s.split(' ')
  end

  def self.to_ia
    InputLine.to_sa.map(&:to_i)
  end

  def self.to_fa
    InputLine.to_sa.map(&:to_f)
  end
end

Mod = 1e+9.to_i + 7

def main(argv)
  n = InputLine.to_i
  a = InputLine.to_ia

  s = [0] * (n + 1)
  n.times{|i| s[i + 1] = (s[i] + a[i]) % Mod}

  t = 0
  n.times do |i|
    p = (a[i] * (s[n] + Mod - s[i + 1])) % Mod
    t = (t + p) % Mod
  end
  puts t.to_s
end

if self.to_s == 'main' then
  main(ARGV)
end


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

A = 10 ** 9 + 7
result = 0
base = 0
(n-2).downto(0) do |i|
  base += arr[i+1]
  tmp = (base * arr[i]) % A
  result += tmp
  result %= A
end

puts result


n = gets.to_i
a = gets.split.map(&:to_i)
M = 1000000007
sum = 0
n.times do |i|
  (i+1..n-1).each do |j|
    sum += (a[i] * a[j]) % M
    sum %= M
  end
end
puts sum


#include<bits/stdc++.h>

using namespace std;
using ll = long long int;
using lc = complex<double>;

int main(void) {
    constexpr ll MOD = 1e9 + 7;
    constexpr double PI = acos(-1);
    cout << fixed << setprecision(32);
    cin.tie(0); ios::sync_with_stdio(false);

    ll n;
    cin >> n;
    vector<ll> a(n);
    for(auto &e: a) cin >> e;
    vector<ll> b = a;

    for(ll i=1; i<n; i++)
        b[i] = (b[i-1] + a[i]) % MOD;

    ll res = 0;
    for(ll i=1; i<n; i++)
        (res += (b[i-1] * a[i]) % MOD) %= MOD;
    cout << res << endl;
}


# エラトステネスの篩で素数列挙して高速に素因数分解したい！
# ref: https://atcoder.jp/contests/abc177/editorial/82
class PrimeDivWithSieve
  def initialize(n)
    @sieve = []
    @elements = {}
    (2..n).each do |i|
      next if @elements[i]
      @sieve << i
      @elements[i] = [i]

      sieve_target = i * 2
      while sieve_target <= n do
        if @elements[sieve_target]
          @elements[sieve_target].push(i)
        else
          @elements[sieve_target] = [i]
        end
        sieve_target += i
      end
    end
  end

  def element(num)
    @elements[num] || [num]
  end
end

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

divisor = PrimeDivWithSieve.new(1_000_000)
common_elms = divisor.element(arr[0])
all_elms = {}
common_elms.each do |i|
  all_elms[i] = true
end

pair = true
set = false
arr[1..-1].each do |i|
  crr_elms = divisor.element(i)
  if pair
    crr_elms.each do |i|
      break pair = false if all_elms[i]
      all_elms[i] = true
    end
  end
  if !set
    common_elms = (common_elms & crr_elms)
    set = common_elms.empty?
  end

  break if set && !pair
end

if pair
  puts "pairwise coprime"
elsif set
  puts "setwise coprime"
else
  puts "setwise coprime"
end

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.


# エラトステネスの篩で素数列挙して高速に素因数分解したい！
# ref: https://atcoder.jp/contests/abc177/editorial/82
class PrimeDivWithSieve
  def initialize(n)
    @sieve = []
    @elements = {}
    (2..n).each do |i|
      next if @elements[i]
      @sieve << i
      @elements[i] = [i]

      sieve_target = i * 2
      while sieve_target <= n do
        if @elements[sieve_target]
          @elements[sieve_target].push(i)
        else
          @elements[sieve_target] = [i]
        end
        sieve_target += i
      end
    end
  end

  def element(num)
    @elements[num] || [num]
  end
end

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

divisor = PrimeDivWithSieve.new(1_000_000)
common_elms = divisor.element(arr[0])
all_elms = {}
common_elms.each do |i|
  all_elms[i] = true
end

pair = true
set = false
arr[1..-1].each do |i|
  crr_elms = divisor.element(i)
  if pair
    crr_elms.each do |i|
      break pair = false if all_elms[i]
      all_elms[i] = true
    end
  end
  if !set
    common_elms = (common_elms & crr_elms)
    set = common_elms.empty?
  end
end

if pair
  puts "pairwise coprime"
elsif set
  puts "setwise coprime"
else
  puts "not coprime"
end


class PrimeDivWithSieve
  def initialize(n)
    @sieve = [] # nまでの素数を入れる
    @min_div = {} # keyの値の最小の素因数を入れる
    @elm = {}
    @cache = {}
    # 他を篩落とし得る素数はsqrtを上限にできる
    (2..Math.sqrt(n).floor).each do |i|
      next if @min_div[i] # ここに値が入ってる = ふるい落とされている
      @sieve << i # ふるい落とされずに来たらそいつは素数

      sieve_target = i * i
      while sieve_target <= n do
        @min_div[sieve_target] ||= i
        sieve_target += i
      end
    end
    (Math.sqrt(n).floor.next..n).each do |i|
      next if @min_div[i]
      @sieve << i
    end
  end

  # Integer#prime_division と同じ値を返すようにする
  # https://docs.ruby-lang.org/ja/latest/method/Integer/i/prime_division.html
  def prime_division(num)
    return [[num, 1]] if !@min_div[num] # 素数のときすぐ返す

    return_array = [] # [[a, x], [b, y]] <=> num = a^x * b^y
    while num > 1 do
      prime = @min_div[num] # 最小の素因数, nil => numが素数
      break return_array.push([num, 1]) if !prime

      div_total = 0
      while num % prime == 0 do
        num /= prime
        div_total += 1
      end
      return_array.push([prime, div_total])
    end

    return_array
  end

  def prime_list
    @sieve
  end

  def elms(num)
    @elm[num] ||= prime_division(num).map(&:first)
  end
end

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

divisor = PrimeDivWithSieve.new(1_000_010)

common_elms = divisor.elms(arr[0])
all_elms = {}
common_elms.each do |i|
  all_elms[i] = true
end

pair = true
set = false
arr[1..-1].each do |i|
  crr_elms = divisor.elms(i)
  if pair
    crr_elms.each do |i|
      break pair = false if all_elms[i]
      all_elms[i] = true
    end
  end
  if !set
    common_elms = (common_elms & crr_elms)
    set = common_elms.empty?
  end
end

if pair
  puts "pairwise coprime"
elsif set
  puts "setwise coprime"
else
  puts "not coprime"
end


class PrimeDivWithSieve
  def initialize(n)
    @sieve = [] # nまでの素数を入れる
    @min_div = {} # keyの値の最小の素因数を入れる
    @elm = {}
    # 他を篩落とし得る素数はsqrtを上限にできる
    (2..Math.sqrt(n).floor).each do |i|
      next if @min_div[i] # ここに値が入ってる = ふるい落とされている
      @sieve << i # ふるい落とされずに来たらそいつは素数

      sieve_target = i * i
      while sieve_target <= n do
        @min_div[sieve_target] ||= i
        sieve_target += i
      end
    end
    (Math.sqrt(n).floor.next..n).each do |i|
      next if @min_div[i]
      @sieve << i
    end
  end

  # Integer#prime_division と同じ値を返すようにする
  # https://docs.ruby-lang.org/ja/latest/method/Integer/i/prime_division.html
  def prime_division(num)
    return [[num, 1]] if !@min_div[num] # 素数のときすぐ返す

    return_array = [] # [[a, x], [b, y]] <=> num = a^x * b^y
    while num > 1 do
      prime = @min_div[num] # 最小の素因数, nil => numが素数
      break return_array.push([num, 1]) if !prime

      div_total = 0
      while num % prime == 0 do
        num /= prime
        div_total += 1
      end
      return_array.push([prime, div_total])
    end

    return_array
  end

  def prime_list
    @sieve
  end

  def elms(num)
    @elm[num] ||= prime_division(num).map(&:first)
  end
end

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

divisor = PrimeDivWithSieve.new(1_000_000)

common_elms = divisor.elms(arr[0])
all_elms = {}
common_elms.each do |i|
  all_elms[i] = true
end

pair = true
set = true
arr[1..-1].each do |i|
  crr_elms = divisor.elms(i)
  common_elms = common_elms & crr_elms if set # どちらにもある要素が共通因数
  if pair
    crr_elms.each do |i|
      break pair = false if all_elms[i]
      all_elms[i] = true
    end
  elsif set
    set = false if common_elms.empty?
  end
end

if pair
  puts "pairwise coprime"
elsif set
  puts "setwise coprime"
else
  puts "not coprime"
end


N = gets.to_i
A = gets.split.map(&:to_i)
Amax = A.max
D = Array.new(Amax + 1, &:itself)
(2 .. Integer.sqrt(Amax)).each do |x|
  next if D[x] < x
  s = x
  while s <= Amax
    D[s] = x
    s += x
  end
end

dp = Array.new(A.max + 1, 0)
A.each do |a|
  while D[a] > 1
    m = D[a]
    dp[m] += 1
    while D[a] == m
      a /= m
    end
  end
end

dpmax = dp.max
if dpmax <= 1
  puts "pairwise coprime"
elsif dpmax == N
  puts "non coprime"
else
  puts "setwise coprime"
end


require 'prime'
n = gets.to_i
nums = gets.split.map(&:to_i).sort
hash = Hash.new(0)
gcd = nums.first
set = false
time = Time.now
nums.shuffle!
interrupted = false
nums.each_with_index do |num, index|
  gcd = gcd.gcd(num)
  next if interrupted
  if index % 1000 == 0
    unless Time.now - 1.8 < time
      interrupted = true
    end
  end
  unless set
    Prime.prime_division(num).each do |k, _|
      hash[k] += 1
      set = true if hash[k] > 1
    end
  end
end
if gcd > 1
  puts "not coprime"
else
  if set
    puts "setwise coprime"
  else
    puts "pairwise coprime"
  end
end


require 'prime'

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

exist = Array.new(1000000)
g = 0
f = true

a.each do |e|
    if f
        e.prime_division.each do |k,_|
            if exist[k]
                f = false
                break
            else
                exist[k] = true
            end
        end
    end
    g = g.gcd(e)
end

if f
    puts "pairwise coprime"
elsif g == 1
    puts "setwise coprime"
else
    puts "not coprime"
end


eval'A=#'+`tr ' ' ,`
h=A.tally
puts (2..1e6).any?{|i|i.step(1e6,i).sum{h[_1]||0}>1}?A.reduce(:gcd)>1?"setwise":"not":"pairwise","coprime"


#!ruby -rprime
z,d=eval"N,*A="+`dd`.split*?,
A.map{d=d.gcd _1;z&&Prime.prime_division(_1).map{|x,|z&&=!$*[x];$*[x]=0}}
puts d>1?:not:z ?:pairwise: :setwise,:coprime


#!ruby -narprime
A=$F.map &:to_i
d=A.tally
A[1]&&print(Prime.each(1e6).all?{|r|a=(r..10**6).step(r).sum{d[_1]||0}<2}?:pairwise:A.reduce(:gcd)<2?:setwise: :not,' coprime')


h,w,m = gets.chomp.split.map(&:to_i)
targets_h = []
targets_w = []
sl = []
m.times do
  h,w = gets.chomp.split.map(&:to_i)
  targets_h << h
  targets_w << w
  sl << [h,w]
end
maxh = targets_h.uniq.max_by{|x| targets_h.count(x)}
maxw = targets_w.uniq.max_by{|y| targets_w.count(y)}
cnt = targets_h.count(maxh) + targets_w.count(maxw)
cnt -= 1 if sl.include?([maxh,maxw])
p cnt

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4

Sample Output 3

6


s,*X=$<.map{_1.split.map &:to_i}
A,B=X.transpose.map{|x|c=x.tally;d=c.map{_2}.max;c.filter{_2==d}}
Y=X.tally
p A.all?{|a,c|B.all?{s=c+_2;Y[[a,_1]]}}?s-1:s


line = gets()
h, w, m = line.chomp.split(' ').map{|i| i.to_i}

point =[]
m.times do |i|
    line = gets().chomp
    hi, wi = line.split(' ').map { |e| e.to_i }
    point.push([hi-1, wi-1])
end

total =Hash.new
hcount = Array.new(h) {|i| i = 0}
wcount = Array.new(w) {|i| i = 0}

m.times do |i|
    tmp = point[i]
    y = tmp[0]
    x = tmp[1]

    total[y*w + x] = 1
    hcount[y] += 1
    wcount[x] += 1
end

max_b = 0
#area = h*w
h.times do |j|
    w.times do |i|
        tmp = hcount[j] + wcount[i]
        #if total[i + j*w] == 1
        if total.keys.include?(j*w+i)
            tmp -= 1
        end
        if tmp > max_b
            max_b = tmp
        end
    end
end

puts(total)
print(max_b)


require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
h,w,m = gets.chomp.split.map(&:to_i)
set = Set.new
rows = Array.new(h, 0)
cols = Array.new(w, 0)
m.times do
  y,x = gets.chomp.split.map{|e| e.to_i - 1}
  rows[y] += 1
  cols[x] += 1
  set.add [y, x]
end

rowmax = rows.max
colmax = cols.max

rows = rows.zip((0...h).to_a)
cols = cols.zip((0...w).to_a)

rows0 = rows.select{|row| row[0] == rowmax}
cols0 = cols.select{|col| col[0] == colmax}

rows0.each do |row_v, row_i|
  cols0.each do |col_v, col_i|
    unless set.include? [row_i, col_i]
      puts row_v + col_v
      exit
    end
  end
end
puts rows0[0][0] + cols0[0][0] - 1


h, w, m = gets.split.map(&:to_i)
nodes = []
h_list = Array.new(h+1) { [] }
w_list = Array.new(w+1) { [] }
m.times do |i|
  nodes[i] = gets.split.map(&:to_i)
  h_list[nodes[i][0]] << i
  w_list[nodes[i][1]] << i
end
h_list.compact!
h_list.sort_by!{_1.length * -1}
h_last_idx = 0
h_list.each.with_index { |l, idx| break if l.length < h_list.first.length - 1; h_last_idx = idx; }
w_list.compact!
w_list.sort_by!{_1.length * -1}
w_last_idx = 0
w_list.each.with_index { |l, idx| break if l.length < w_list.first.length - 1; w_last_idx = idx; }
max = 0
h_list[0..h_last_idx].each do |hl|
  w_list[0..w_last_idx].each do |wl|
    max = [max, (hl + wl).uniq.length].max
  end
end
puts max


h,w,m = gets.split.map(&:to_i)
line_count = Array.new(w){0}
row_count = Array.new(h){0}
counts = Array.new(h){[0]*w}

m.times do
  hi,wi = gets.split.map(&:to_i)
  row_count[hi-1] += 1
  line_count[wi-1] += 1
  counts[hi-1][wi-1] -= 1
end

max = 0
row_count.each_with_index do |r,i|
  max_l = 0
  line_count.each_with_index do |l,j|
    counts[i][j] += r + l
    max_l = [max_l,counts[i][j]].max
  end
  max = [max,max_l].max
end
puts max


h,w,m = gets.split.map(&:to_i)
tate = Array.new(h,0)
yoko = Array.new(w,0)
z = Array.new(h).map{Array.new(w,true)}

for i in 0...m
  temp = gets.split.map(&:to_i)
  temp[0]-=1
  temp[1]-=1
  tate[temp[0]] += 1
  yoko[temp[1]] += 1
  z[temp[0]][temp[1]] = false
end

tate1 = Array.new(0)
yoko1 = Array.new(0)

max_t = tate.max
max_y = yoko.max

for i in 0...h
  if max_t==tate[i]
    tate1.push i
  end
end
for i in 0...w
  if max_y==yoko[i]
    yoko1.push i
  end
end

for i in tate1
  for j in yoko1
    if z[i][j]
      puts max_t+max_y
      return
    end
  end
end
puts max_t+max_y-1


N = gets.chomp.to_i
p N.round(-3, half: :up) - N

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


x = gets.to_i
ans = 0
while x > 0 do
  x -= 1000
  ans += 1
end

puts ans


a = gets.to_i

b = 1000 - a%1000

if b == 1000
	puts 0
else
	puts b
end


n = gets.chomp.to_i

while n > 1000 do
  n -= 1000
end

puts 1000 - n


syouhin = gets.chomp.to_i
if syouhin%1000
  puts 0
  exit
else
  puts 1000-(syouhin%1000)
end


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

def ar2(s1,s2,de=nil) Array.new(s1){Array.new(s2,de)} end
def ar3(s1,s2,s3,de=nil) Array.new(s1){Array.new(s2){Array.new(s3,de)}} 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(:+).to_i end
def ceil(a,b) (a.to_f/b).ceil 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 rui(ar) s=[0]; ar.size.times{|i| s<<s[-1]+ar[i]}; s end
def rev_rui(ar) s=[0]; ar.size.times.reverse_each{|i| s<<s[-1]+ar[i]}; s end

def puts_yesno(b) puts(b ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def pu(h) begin; require './../nemi_lib/debug.rb'; puts_val(h); rescue LoadError; end; end
########### ( ˘ω˘ )ｽﾔｧ… ###########

# Genetic Algorithm
class GA
  # ログ取りたい
  def initialize(time:2, item_length:10, item_size:10, range:0..100)
    @start_time = Time.now
    @time_limit = time - 0.1
    @item_size = item_size
    @item_length = item_length
    @range = range
    @superior = nil

    @items = generate
  end

  def execute
    evaluate
    while true
      change
      sudden_change
      evaluate
      @superior = @items[0] if !@superior || @superior.point.to_i < @items[0].point
      break unless in_time?
    end

    @superior
  end

  private

  # 初期値生成
  def generate
    items = []
    gene = Struct.new(:ar, :point)
    @item_size.times do |i|
      ar = []
      @item_length.times do |j|
        ar << rand(@range)
      end
      items << gene.new(ar, 0)
    end
    items
  end

  # 交叉
  def change
    gene = Struct.new(:ar, :point)
    l = @items.size/2
    l.times do
      pat1 = @items.shift.ar
      pat2 = @items.shift.ar
      lp = @item_length
      @items << gene.new((pat1[0..lp/2] + pat2[lp/2+1..-1]),0)
      @items << gene.new((pat2[0..lp/2] + pat1[lp/2+1..-1]),0)
    end
  end

  # 突然変異
  def sudden_change
    ratio = 5 #percent
    count = @item_length * @item_size * ratio / 100
    count.times do |i|
      target_i = rand(@item_size)
      pos_i = rand(@item_length)
      val = rand(@range)
      @items[target_i].ar[pos_i] = val
    end
  end

  # 評価
  def evaluate
    # TODO: 実装する
    # 例: 次の要素との差分の２乗が大きくなる方がいい

    @item_size.times do |i|
      prev=0
      sum=0
      @item_length.times do |j|
        sum+= (@items[i].ar[j]-prev)**2
        prev = @items[i].ar[j]
      end
      @items[i].point=sum
    end

    sort!
  end

  # pointに従ってソート
  def sort!
    @items.sort_by!{|a|-a.point}.to_a
  end

  def in_time?
    @time_limit> Time.now - @start_time
  end

end

class GAA < GA
  def initialize(time:2, item_length:100, item_size:10, range:1..26,c:,s:)
    @c=c
    @s=s
    super(time:2, item_length:5, item_size:10, range:1..26)
  end

  def evaluate
    @item_size.times do |i|
      prev=0
      sum=0
      lasts={}
      @item_length.times do |day|
        con = @items[i].ar[day]
        lasts[con]=day
        sum+=@s[day][con-1]
        (1..26).each do |k|
          last=lasts[k].to_i
          sum-=@c[k-1]*(day-last)
        end
      end
      @items[i].point=sum
    end
    sort!
  end
end

d=gi
c=gsmi
s=d.times.map{gsmi}

ga=GAA.new(item_size:d,c:c,s:s)
ans=ga.execute
puts ans.ar

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for D days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type i on day d will increase the satisfaction by s_{d,i}.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type i has an integer c_i, and at the end of each day d=1,2,...,D, the satisfaction decreases as follows. Let \mathrm{last}(d,i) be the last day before day d (including d) on which a contest of type i was held. If contests of type i have never been held yet, we define \mathrm{last}(d,i)=0. At the end of day d, the satisfaction decreases by \sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i)).

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day D is S, you will get a score of \max(10^6 + S, 0).
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

Each s_{d,i} is an integer satisfying 0\leq s_{d,i} \leq 20000.

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

Let t_d (1\leq t_d \leq 26) be the type of the contest that will be held at day d.
Print D integers t_d to Standard Output in the following format:

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

Each integer c_i and s_{d,i} is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.


D = gets.to_i
C = gets.chomp.split.map(&:to_i)
s = D.times.map{gets.split.map(&:to_i)}
c = Array.new(26, 0)
t = []

(0..D-1).each do |i|

  (0..25).each do |l|
    c[l] += C[l]
  end
ans = 0
boder = s[i][0]+6*c[0]

  (1..25).each do |e|
    if s[i][e]+6*c[e] >= boder
      ans = e
      boder = s[i][e]+6*c[e]
    end
  end
c[ans] = 0
puts ans+1
end


D = gets.to_i
C = gets.chomp.split.map(&:to_i)
s = D.times.map{gets.split.map(&:to_i)}
c = Array.new(26, 0)
t = []

(0..D-1).each do |i|
ans = 0
boder = s[i][0]+c[0]

  (0..25).each do |l|
    c[l] += C[l]
  end
  (1..25).each do |e|
    if s[i][e]+c[e] >= boder
      ans = e
      boder = s[i][e]+c[e]
    end
  end
c[ans] = 0
t << ans+1
last = boder
end


D = gets.to_i
C = gets.chomp.split.map(&:to_i)
s = D.times.map{gets.split.map(&:to_i)}
c = Array.new(26, 0)
t = []

(0..D-1).each do |i|
ans = 0
boder = s[i][0]+c[0]

  (0..25).each do |l|
    c[l] += C[l]
  end
  (1..25).each do |e|
    if s[i][e]+c[e] >= boder
      ans = e
      boder = s[i][e]+c[e]
    end
  end
c[ans] = 0
t << ans+1
last = boder
end

Timeout.timeout(1)


n, m, k = gets.split.map(&:to_i)
a_arr = gets.split.map(&:to_i)
b_arr = gets.split.map(&:to_i)

sum = 0
sum_a_arr = [[0, 0]]
a_arr.each_with_index do |num, i|
  sum += num
  sum_a_arr << [sum, i + 1]
end

sum = 0
sum_b_arr = [[0, 0]]
b_arr.each_with_index do |num, i|
  sum += num
  sum_b_arr << [sum, i + 1]
end

max = 0
ind = 0
sum_a_arr.reverse_each do |num, count|
  next if num > k

  c = count
  while ind < b_arr.length
    num2, count2 = sum_b_arr[ind]
    break if num + num2 > k

    ind += 1
    c = count + count2
  end

  max = c if max < c
end

p max

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.


n,m,k = gets.chomp.split(' ').map(&:to_i)
a = gets.chomp.split(' ').map(&:to_i).sort
b = gets.chomp.split(' ').map(&:to_i).sort
count = 0
while true
  if a[0] <= b[0] && a[0] <= k
    k -= a[0]
    a.shift()
    a << 200001 if a == []
    count += 1
  elsif a[0] > b[0] && b[0] <= k
    k -= b[0]
    b.shift()
    b << 200001 if b == []
    count += 1
  else
    break
  end
  # p a,b,k
end
puts count


n,m,k=gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(' ').map(&:to_i)
b = gets.chomp.split(' ').map(&:to_i)

ans = 0
c = Array.new(n+1){0}
d = Array.new(m+1){0}

n.times do |i|
  c[i+1] = c[i] + a[i]
end
m.times do |l|
  d[l+1] = d[l] + b[l]
end

bm = m
0.step(n) do |i|
  break if c[i] > k
  while d[bm] > k - c[i]
   bn -= 1
  end
  if ans < bm + i
    ans = bm + i
  end
end
puts ans


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

queue = [[0, 0, k, 0]]
result = 0
while true
    a, b, dk, c = queue.shift
    if a < table_a.length and dk >= table_a[a]
        new_item = [a+1, b, dk - table_a[a], c + 1]
        index = queue.rindex{|item| item[-2] <= new_item[-2]}
        if !index.nil?
            queue.insert(index, new_item) if index == 0 or queue[index-1][0,2] != new_item[0,2]
        else
            queue.push(new_item) if !queue.any? or queue[-1][0,2] != new_item[0,2]
        end
    end

    if b < table_b.length and dk >= table_b[b]
        new_item = [a, b+1, dk - table_b[b], c + 1]
        index = queue.rindex{|item| item[-2] <= new_item[-2]}
        if !index.nil?
            queue.insert(index, new_item) if index == 0 or queue[index-1][0,2] != new_item[0,2]
        else
            queue.push(new_item) if !queue.any? or queue[-1][0,2] != new_item[0,2]
        end
    end

    unless queue.any?
        result = c
        break
    end
end

puts result


N, M, K = gets.chomp.split.map(&:to_i)
aAry = gets.chomp.split.map(&:to_i)
bAry = gets.chomp.split.map(&:to_i)

ans = 0
aTotal = 0
(N + 1).times do |n|
    aTotal += aAry[n - 1] unless n == 0
    break if aTotal > K

    bTotal = 0
    (M + 1).times do |m|
        bTotal += bAry[m - 1] unless m == 0
        break if aTotal + bTotal > K
        ans = n + m if ans < n + m
        # puts "n, m = " + n.to_s + ", " + m.to_s + " now."
    end
end
puts ans

# ans = 0
# (N + 1).times do |n|
#     (M + 1).times do |m|
#         if aAry[0, n].sum + bAry[0, m].sum <= K then
#             ans = n + m if ans < n + m
#         end
#     end
# end
# puts ans


require "pp"

n, m, k = gets.split(" ").map(&:to_i)
a_i = gets.split(" ").map(&:to_i)
b_i = gets.split(" ").map(&:to_i)

time = 0
res = []
while time <= k && !(a_i.empty? && b_i.empty?) do
    if a_i.empty? then
        time += b_i[0]
        res << b_i[0]
        b_i = b_i[1..-1]
        next
    end

    if b_i.empty? then
        time += a_i[0]
        res << a_i[0]
        a_i = a_i[1..-1]
        next
    end

    if a_i[0] <= b_i[0] then
        time += a_i[0]
        res << a_i[0]
        a_i = a_i[1..-1]
        next
    else
        time += b_i[0]
        res << b_i[0]
        b_i = b_i[1..-1]
        next
    end
end

if time <= k then
    puts res.length
else
    puts res.length - 1
end


def binarySearch(arr, key)
    left = -1
    right = arr.size
    while (right-left).abs > 1
        mid = (right+left) / 2
        if arr[mid] > key then
            right = mid
        else
            left = mid
        end
    end
    return left
end

n, m, k = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)
ruiseki_a = [0]
ruiseki_b = [0]
ans = 0
n.times do |i|
    ruiseki_a << a[i] + ruiseki_a[i]
end
m.times do |i|
    ruiseki_b << b[i] + ruiseki_b[i]
end
(n+1).times do |i|
    j = binarySearch(ruiseki_b, k - ruiseki_a[i])
    break if j == -1
    ans = ans < i+j ? i+j : ans
end
puts ans


N,M,K = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)

max = 0

a = [0]
b = [0]
A.each_with_index do |n,i|
  a << a[i] + n
end
B.each_with_index do |n,i|
  b << b[i] + n
end

ans = 0
j = M

0.upto(N) do |i|
  if a[i] > K
    break
  end

  while b[j] > K - a[i] do
    j -= 1
  end
  c = i + j
  ans = c if c > ans
end

puts ans


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

ans = 0
now = 0

loop do
  a = as.first
  b = bs.first
  break if [a, b].all?(nil)

  if as.empty?
    t = bs.shift
  elsif bs.empty?
    t = as.shift
  else
    if a >= b
      t = bs.shift
    else
      t = as.shift
    end
  end
  break if now + t > k
  now += t

  ans += 1
end

puts ans


def main
  n,m,k = gets.chomp.split(" ").map(&:to_i)
  as = gets.chomp.split(" ").map(&:to_i)
  bs = gets.chomp.split(" ").map(&:to_i)

  time = 0
  cnt = 0
  i_a = 0
  i_b = 0
  loop do
    if i_a == as.size && i_b == bs.size
      break
    elsif i_a == as.size
      time += bs[i_b]
      i_b += 1
    elsif i_b == bs.size || as[i_a] <= bs[i_b]
      time += as[i_a]
      i_a += 1
    else
      time += bs[i_b]
      i_b += 1
    end
    if time <= k
      cnt += 1
    else
      break
    end
  end
  puts cnt
end

main


n, m, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)

count = 0
while true
  break if k <= 0
  break if a.empty? && b.empty?
  #p "#{a[0]}, #{b[0]}"
  time = if a.empty?
           b.shift
         elsif b.empty?
           a.shift
         elsif a[0] <= b[0]
           a.shift
         else
           b.shift
         end
  if k >= time
    count += 1
    k -= time
  else
    break
  end
end

puts count


inputs = readlines
N,M,k = inputs[0].chomp.split(' ').map(&:to_i)
Ai = inputs[1].chomp.split(' ').map(&:to_i)
Bi = inputs[2].chomp.split(' ').map(&:to_i)

count = 0
max_count = 0

Aii = []
Bii = []

Ai.each_with_index do |a, idx|
  if idx == 0
    Aii[0] = Ai[0]
  else
    Aii[idx] = Aii[idx-1] + Ai[idx]
    break if Aii[idx] > k
  end
end
Aii.unshift(0)

Bi.each_with_index do |b, idx|
  if idx == 0
    Bii[0] = Bi[0]
  else
    Bii[idx] = Bii[idx-1] + Bi[idx]
    break if Bii[idx] > k
  end
end
Bii.unshift(0)

Aii.each_with_index do |a, aidx|
  count = 0
  Bii.each_with_index do |b, bidx|
    if a + b <= k
      count = aidx + bidx
    elsif a + b > k
      break
    end
    max_count = [max_count,count].max
  end
end

puts max_count


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

a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
count = 0

while k > 0 do
  c = a[0]
  d = b[0]
  e = []
  unless c.nil?
    e << c
  end
  unless d.nil?
    e << d
  end

  f = e.min
  if e.min == c
    a.delete_at(0)
  elsif e.min == d
   b.delete_at(0)
  end
  k = k - f
  if k >= 0
    count += 1
  end

end

puts count


#!/usr/bin/env ruby
n, m, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
b = gets.chomp.split.map(&:to_i)

ans = 0
sum_time = 0
i = 0
j = 0

while true
  break if i == n && j == m

  if i == n
    sum_time += b[j]
    break if sum_time > k
    j += 1
    ans += 1
  elsif j == m
    sum_time += a[i]
    break if sum_time > k
    i += 1
    ans += 1
  else
    if a[i] < b[j]
      sum_time += a[i]
      break if sum_time > k
      i += 1
      ans += 1
    else
      sum_time += b[j]
      break if sum_time > k
      j += 1
      ans += 1
    end
  end
end

puts ans


n,m,k = gets.split.map &:to_i
as = gets.split.map &:to_i
bs = gets.split.map &:to_i

remain = k

ind = 0

as.each.with_index(1) {|a, i|
	if remain >= a then
		remain -= a
		ind = i
	else
		break
	end
}

b_ind = 0

bs.each.with_index(1) { |b, i|
	if remain >= b then
		remain -= b
		b_ind = i
	else
		break
	end
}

sum = ind + b_ind

(ind - 1).downto(0){ |i|
	remain += as[i]
	(b_ind...bs.size).each{ |j|
		if remain >= bs[j] then
			remain -= bs[j]
			b_ind += 1
		else
			break
		end
	}

	if i + b_ind > sum then
		sum = i + b_ind
	end
}

puts sum


lines = readlines.join.split.map(&:to_i)

a = lines.shift
b = lines.shift
limit = lines.shift

ad = lines.slice!(0...a)
bd = lines

indexa = 0
indexb = 0
read_count = 0
while limit > 0 do
  if ad[0] == nil
    ad[0] = 999999999999
  end
  if bd[0] == nil
    bd[0] = 999999999999
  end
  if ad[0] > bd[0]
    minus = bd.shift
    if limit < minus
      return p read_count
    end
    limit -= minus
    read_count += 1
  elsif ad[0] < bd[0]
    minus = ad.shift
    if limit < minus
      return p read_count
    end
    limit -= minus
    read_count += 1
  elsif ad[0] == bd[0]
    i = 0
		loop{
        if ad[i+1] == nil
          ad[i+1] = 999999999999
        end
        if bd[i+1] == nil
          bd[i+1] = 999999999999
        end
        if ad[i + 1] > bd[i + 1]
          minus = bd.shift

    	if limit < minus
    	  return p read_count
   		end
          limit -= minus
          read_count += 1
        elsif ad[i + 1] < bd[i + 1]
          minus = ad.shift
            if limit < minus
      			return p read_count
    		end
          limit -= minus
          read_count += 1
          break
        end
          }
    end
  end
end
p read_count


#!/usr/bin/env ruby

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

N, M, K = gets.chomp.split.map(&:to_i)
A = gets.chomp.split.map(&:to_i)
B = gets.chomp.split.map(&:to_i)

def solve(a, b, c, k)
  return c - 1 if k < 0

  return c if a.empty? && b.empty?

  if b.empty?
    a0 = a.shift
    return solve(a, b, c + 1, k - a0)
  end

  if a.empty?
    b0 = b.shift
    return solve(a, b, c + 1, k - b0)
  end

  ac = solve(a[-(a.size-1)..-1], b, c+1, k-a[0])
  bc = solve(a, b[-(b.size-1)..-1], c+1, k-b[0])

  if ac >= bc
    return ac
  else
    return bc
  end
end

puts solve(A, B, 0, K)


N,M,K=gets.split.map(&:to_i)

as = gets.split.map(&:to_i).reverse + gets.split.map(&:to_i)

l = 0
r = N
sum = as[0...r].inject(:+)

max = 0
while r < N+M
    if K < sum
        sum -= as[l]
        l += 1
    else
        sum += as[r]
        r += 1
    end

    if sum <= K
        len = r-l
        max = len if max < len
    end
end

puts max


n,m,k = gets.chomp.split(' ').map{|e| e.to_i}
sum = 0
a = gets.chomp.split(' ').map{|e| sum += e.to_i}
a << 0
sum = 0
b = gets.chomp.split(' ').map{|e| sum += e.to_i}
b << 0
max_book = 0
# chose one, two, three... books from desk A
for book_a in 0..n
  k_a = a[book_a-1]
  next if k_a > k
  k_remain = k - k_a
  for book_b in 0..m
    k_b = b[book_b-1]
    break if k_b > k_remain
    book = book_a + book_b
    max_book = book if book > max_book
  end
end
puts max_book


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

def ar2(s1,s2,de=nil) Array.new(s1){Array.new(s2,de)} end
def ar3(s1,s2,s3,de=nil) Array.new(s1){Array.new(s2){Array.new(s3,de)}} 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(:+).to_i end
def ceil(a,b) (a.to_f/b).ceil 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 rui(ar) s=[0]; ar.size.times{|i| s<<s[-1]+ar[i]}; s end
def rev_rui(ar) s=[0]; ar.size.times.reverse_each{|i| s<<s[-1]+ar[i]}; s end

def puts_yesno(b) puts(b ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def pu(h) begin; require './../nemi_lib/debug.rb'; puts_val(h); rescue LoadError; end; end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n,m,k=gsmi
a=gsmi
b=gsmi

while true
  if a.empty?&&b.empty?
    break
  elsif a.empty?
    k-=b.shift
  elsif b.empty?
    k-=a.shift
  elsif a[0]<= b[0]
    k-=a.shift
  else
    k-=b.shift
  end

  if k>0
    cnt+=1
  elsif k==0
    cnt+=1
  else
    break
  end
end

puts cnt


require 'prime'

n = gets.to_i
f = Array.new(n+1, 1)

2.upto(n) do |i|
    i.step(n, i) do |j|
        f[j] += 1
    end
end

puts f.each_with_index.inject(0) {|r, (v, i)| r += v * i}

Score : 400 points

Problem Statement

For a positive integer X, let f(X) be the number of positive divisors of X.

Given a positive integer N, find \sum_{K=1}^N K\times f(K).

Constraints

1 \leq N \leq 10^7

Input

Input is given from Standard Input in the following format:

N

Output

Print the value \sum_{K=1}^N K\times f(K).

Sample Input 1

4

Sample Output 1

23

We have f(1)=1, f(2)=2, f(3)=2, and f(4)=3, so the answer is 1\times 1 + 2\times 2 + 3\times 2 + 4\times 3 =23.

Sample Input 2

100

Sample Output 2

26879

Sample Input 3

10000000

Sample Output 3

838627288460105

Watch out for overflows.


n = gets.to_i
arr = Array.new(n+1,0)
n.times do |i|
  x = i+1
  while x <= n
    arr[x] += 1
    x += i+1
  end
end
ans = 0
n.times do |i|
  ans += (i+1) * arr[i+1]
end
puts ans


N = gets.to_i

FF = {}

SUM = {}

def divisor(num)
  ff = FF[num]
  return ff if ff
  result = []
  i = 1
  while i <= num do
    remainder = num % i
    if remainder == 0
      result << i
    end
    i += 1
  end
  result_size =  result.size
  FF[num] = result_size
  result_size
end

def sum_f(x)
  sum_x = SUM[x]
  return sum_x if sum_x
  if x == 1
    result = divisor(x)
    SUM[x] = result
    return result
  end
  result = sum_f(x - 1) + x * divisor(x)
  SUM[x] = result
  result
end

ans = sum_f(N)

puts ans


require 'prime'

class Prime
    def each_divisor(n, &block)
        pf = prime_division(n)
        num = -> { pf.inject(1) { |prod, (_, exp)| prod * exp.succ } }
        Enumerator.new(num) { |y| __each_divisor__(1, pf, &y.method(:<<)) }
                  .tap { |enum| enum.each(&block) }
    end

    private def __each_divisor__(d, ary, &block)
        return yield(d) if ary.empty?

        ary = ary.dup
        prime, exp = ary.pop
        0.upto(exp) { __each_divisor__(d, ary, &block); d *= prime }
    end
end

N = gets.to_i

prime = Prime.instance
res = 0
(1..N).each do |i|
  res += i * prime.each_divisor(i).size
end
p res


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

def ar2(s1,s2,de=nil) Array.new(s1){Array.new(s2,de)} end
def ar3(s1,s2,s3,de=nil) Array.new(s1){Array.new(s2){Array.new(s3,de)}} 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(:+).to_i end
def ceil(a,b) (a.to_f/b).ceil 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 rui(ar) s=[0]; ar.size.times{|i| s<<s[-1]+ar[i]}; s end
def rev_rui(ar) s=[0]; ar.size.times.reverse_each{|i| s<<s[-1]+ar[i]}; s end

def puts_yesno(b) puts(b ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def pu(h) begin; require './../nemi_lib/debug.rb'; puts_val(h); rescue LoadError; end; end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi

sum=0
1.upto n do |i|
  d=n/i
  sum+=((d+1)*d/2)*i
end

puts sum


gets.to_i
line = gets.split.map(&:to_i)
max = line.max
ary = Array.new(max + 1, 0)

line.each { |l| l.step(max, l) { |n| ary[n] += 1 } }

puts line.count { |i| ary[i] == 1 }

Score : 400 points

Problem Statement

Given is a number sequence A of length N.

Find the number of integers i \left(1 \leq i \leq N\right) with the following property:

For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the answer.

Sample Input 1

5
24 11 8 3 16

Sample Output 1

3

The integers with the property are 2, 3, and 4.

Sample Input 2

4
5 5 5 5

Sample Output 2

0

Note that there can be multiple equal numbers.

Sample Input 3

10
33 18 45 28 8 19 89 86 2 4

Sample Output 3

5


require 'set'

def main(str)
  as = str.split("\n")[1].split(" ").map(&:to_i).sort
  sets = Set.new
  nmax = 2 * 10 ** 5
  as.each.with_index.count do |a, i|
    next if sets.include?(a)
    x = a
    loop do
      sets << x
      x += a
      break if x > nmax
    end
    as[i + 1] != a
  end
end

unless ENV["TEST"]
  puts(main($stdin.read.chomp))
  exit(0)
end

require 'minitest/autorun'

class TestA < Minitest::Test
  def test_main
    assert_equal(3, main("5
24 11 8 3 16"))
    assert_equal(0, main("4
5 5 5 5"))
    assert_equal(5, main("10
33 18 45 28 8 19 89 86 2 4"))
  end
end


n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
a = a.sort
INF = (10 ** 6)
arr = Array.new(INF+1,0)
a.each do |i|
    next if arr[i] == 2
    sa = i
    until i > 10 ** 6
        arr[i] += 1
        i += sa
    end
end
count = 0
a.each do |i|
    count += 1 if arr[i] == 1
end
puts count


N,*A = $<.read.split.map(&:to_i)

n,as,bs = 0,A.sort,[]
until as.empty?
	a = as.shift
	n += 1 if a != as[0]
	until as.empty?
		ax = (as[0]+a-1)/a*a
		bs.push(*as.shift(as.index{|_|ax<=_}||as.size))
		as.shift(as.index{|_|ax<_}||as.size)
	end
	as,bs = bs,as
end
p n


N = gets.to_i
A = gets.chomp.split.map(&:to_i).sort!
ary = Array.new(A.max, 0)
ans = 0

A.each do |e|
  ary[e-1] += 1
end

A.each do |e|
  next if ary[e-1] == 0
  ans += 1  if ary[e-1] == 1
  (e-1).step(A.max, e) do |i|
    ary[i] = 0
  end
end

puts ans


N = gets.to_i;
a = gets.split.map(&:to_i);
num = Array.new(1000000, 0);
max = 0;
(0..(N-1)).each{|i| max = a[i] if a[i] > max};
num[0] = 2;
ans = 0;

(0..(N-1)).each do |i|
  j = a[i];
  while(j <= max) do
    num[j] += 1;
    j += i;
  end
end


N = gets.to_i
A = gets.chomp.split(" ").map(&:to_i).sort

ans = 0
amx = A.max
tmp = Array.new(amx+1, true)
(0...N).each{|i|
  next if !tmp[A[i]]
  wk = 1
  while wk * A[i] <= amx do
    tmp[wk*A[i]] = false
    wk += 1
  end
  next if i < N-1 && A[i] == A[i+1]
  ans += 1
}

puts ans


N = gets.to_i
ary = gets.split.map(&:to_i).sort.uniq
if ary.count == 1
  puts 0
else

    nums = Hash.new{|hash, key| hash[key] = 1 }
    ans = Array.new(ary.max + 1).map{|x| x = 0}
    result = 0

    ary.each do |i|
      nums[i]
    end

    ary.each do |j|
      ans[j] = 1
    end

    ary.each do |k|
      result += 1 if ans[k] == 1
      k.step(ary.max, k) do |l|
        ans[l] = 0
      end
    end
    puts result
end


n = gets.to_s.to_i
a = gets.to_s.split.map{|t|t.to_i}.sort

if n == 1 || (a[0] == 1 && a[1] != 1)
  puts 1
  exit
elsif a[0] == 1 && a[1] == 1
  puts 0
  exit
end

MAX_A = a[-1]
hantei = [true] * ( MAX_A + 1 )

a.each_with_index do |t, i|

  if hantei[t]

    hantei[t] = false if t == a[i+1]

    s = t + t
    while s <= MAX_A
      hantei[s] = false
      s += t
    end
  end
end

ans = 0
a.each do |t|
  ans += 1 if hantei[t]
end

puts ans


n = gets.to_i
as = gets.split.map &:to_i
as.sort!

count = 0
n.times do |i|
	a = as[i]
	ok = true
	i.times do |j|
		ok = false if a % as[j] == 0
	end
	ok = false if a == as[i + 1]
	count += 1 if ok
end

p count


n=gets.to_i
a=gets.split.map &:to_i
bad=0
ma=Marshal.load(Marshal.dump(a))
a.each_with_index do |v,idx|
  bflg=false
  ma.delete_at(0)
  ma.each do |v2|
    if  v%v2 == 0 || v2%v == 0
      if v%v2 == 0
        bad+=1
      end
      if v2%v == 0
        bad+=1
      end
      bflg=true
    elsif v == v2
      bad+=1
      bflg=true
    end
    break if bflg
  end
end
ans=(n-bad)
puts ans < 0 ? 0 : ans


n = gets.to_i

cnt = Hash.new(0)
gets.split.map(&:to_i).sort.each do |a|
  cnt[a] += 1
end

a = cnt.keys
a.each do |ai|
  cnt.delete(ai) if cnt[ai] > 1
end

i = 0
n = a.size
while i < n do
  (i+1...n).each do |j|
    cnt.delete(a[j]) if a[j] % a[i] == 0
  end
  a = cnt.keys
  n = a.size
  i += 1
end
p cnt.values.sum


input = defined?(DATA) ? DATA : STDIN

_ = input.gets.to_i
list = input.gets.split(' ').map(&:to_i).sort

hash = {}
list.each do |a|
  if hash[a].nil?
    hash[a] = true
  else
    hash[a] = false
  end
end

list2 = hash.keys
status = hash.values

list2.each_with_index do |a, i|
  next if status[i].nil?
  a_x2 = a * 2
  ((i + 1)...list2.size).each do |j|
    next unless status[j]
    b = list2[j]
    next if b < a_x2
    if b % a == 0
      status[j] = nil
    end
  end
end

puts status.count { |s| s }


require 'prime'

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

x = Array.new(a[-1] + 1)
ans = 0

n.times do |i|
    if a[i] == a[i-1] || (i < n-1 && a[i] == a[i+1])
        next if x[a[i]]
        a[i].step(a[-1], a[i]) {|j| x[j] = true}
        next
    end

    next if x[a[i]]

    ans += 1

    a[i].step(a[-1], a[i]) {|j| x[j] = true}
end

p ans


n = gets.strip.to_i
a = gets.strip.split(" ").map do |i|
  i.to_i
end

a_num={}

a_uniq = a.uniq.sort

a.each do |v|
  a_num[v] = a_num[v].nil? ? 1 : a_num[v]+=1
end

values=[]

a_num.each do |k,v|
  values.push(k)  if v==1
end
sum = n
sum=0
values = values.sort.reverse
values.each do |v|
  f = true
  a_uniq.each do |v1|
    if v%v1 ==0 && v!=v1
      f = false
      a_uniq.delete(v)
    elsif v<v1
      break
    end
  end
  sum +=1 if f
end

print sum


require 'prime'

def divisors(n)
  n.prime_division.inject([1]) do |ary, (p, e)|
    (0..e).map{ |e1| p ** e1 }.product(ary).map{ |a, b| a * b }
  end.sort
end

N = gets.to_i
A = gets.chomp.split(" ").map(&:to_i).sort

ans = 0
(0...N).each{|i|
  next if i > 0 && A[i] == A[i-1]
  next if i < N-1 && A[i] == A[i+1]
  f = true
  divisors(A[i]).each{|d|
    idx = A[0, i].bsearch_index{|x| x >= d}
    next if idx.nil?
    (f = false; break) if d == A[idx]
  }
  ans += 1 if f
}

puts ans


N = $stdin.gets.to_i
A = $stdin.gets.split.map {|i| i.to_i }
A.sort!
Am = {}
A.each do |a|
  Am[a] ||= 0
  Am[a] += 1
end
Ama = Am.to_a
AmaLen = Ama.length
if AmaLen == 1
  puts 0
  exit
end
#$stderr.puts Ama.to_s
cnt = 0
0.upto(AmaLen - 1) do |i|
  ai, ci = Ama[i]
  if ci > 1
    next
  end
  #$stderr.print "#{ai}:"
  inc = 1
  0.upto(i - 1) do |j|
    aj, = Ama[j]
    #$stderr.print " #{aj}[#{ai % aj}]"
    if ai % aj == 0
      inc = 0
      #$stderr.print " *"
      break
    end
  end
  #$stderr.puts
  cnt += inc
end
puts cnt


require 'prime'

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

hash = array.group_by(&:itself).map{ |key, value| [key, value.count] }.to_h

ng = {}

new_arr = []
hash.each do |k,v|
  if v == 1
    new_arr.push(k)
  else
    ng[k] = true
    new_arr.push(k)
  end
end

new_arr.sort!

new_n = new_arr.size

ans = 0
new_n.times do |i|
  next if ng[new_arr[i]]

  if Prime.prime?(new_arr[i])
    ans += 1
    next
  end

  next_flag = false
  i.times do |j|
    if new_arr[i] % new_arr[j] == 0
      next_flag = true
      break
    end

    if new_arr[j] > new_arr[i]/2
      next_flag = true
      ans += 1
      break
    end
  end
  next if next_flag
  ans += 1
end

p ans


#require 'pp'

n = gets.to_i
a_n = gets.split.map(&:to_i)
group = a_n.group_by {|x| x}

#pp group
#p a_n

count = 0
a_n.each_with_index do |a, i|
    #pp "====="
    max = Math.sqrt(a).to_i
    tmp = a
    ok = true
    1.upto(max) do |n|
        #pp n
        if tmp % n == 0
            y = tmp / n
            #pp [n, y]
            if group[n]
                ok = false
                break
            end

            if group[y]
                if group[y].size != 1
                    ok = false
                    break
                elsif group[y][0] != a
                    ok = false
                    break
                end
            end
        end
    end

    if ok
        #pp i
        count += 1
    end
end

pp count


require 'prime'

def _divisors(primes, k)
  Enumerator.new do |y|
    if primes.size == k
      y << 1
    else
      p, e = primes[k]
      _divisors(primes, k + 1).each {|d|
        (e + 1).times {|e1|
          y << p ** e1 * d
        }
      }
    end
  end
end

def divisors(n)
  _divisors(Prime.prime_division(n), 0).to_a.sort
end

n = gets.to_i
a = gets.split.map &:to_i
b = a.map{|i| divisors(i)}
r = 0
for i in 0...n
  aa = a.clone
  aa.delete_at i
  b[i].each do |d|
    if aa.index(d)
      r += 1
      break
    end
  end
end
p r


n = gets.chomp.to_i
a = gets.chomp.split(' ').map{|i| i.to_i }

i = 0
j = 0
count = 0
a.each{|ai|
  count += 1 unless a.any?{|aj|
    # p [count, i, j, ai, aj, ai > aj, ai % aj === 0, ai > aj && ai % aj === 0]
    j += 1
    if i === (j - 1)
      false
    else
      ai > aj && ai % aj === 0
    end
  }
  i += 1
}

puts count


require "prime"

n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
pri = Array.new(n,true)

(0..n-2).each do |i|
	(i+1..n-1).each do |j|
		pri[i] = false if arr[i] % arr[j] == 0
		pri[j] = false if arr[j] % arr[i] == 0
	end
end

puts pri.select{|pr| pr}.length


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

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

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

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

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

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

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

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

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

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

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

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
a = inp
mem = na(10**6+100,false)
mem2 = na(10**6+100,false)
h = {}
max = 10**6
n.times do |i|
  h[a[i]] = i
end
a.sort!
ans = 0

n.times do |i|
  if(mem2[a[i]] == 1)
    mem2[a[i]] += 1
    ans -= 1
  end
  next if(mem[a[i]])
  ans += 1
  ind = a[i]
  mem2[ind] = 1
  pl = a[i]
  while ind < max
    mem[ind] = true
    ind += pl
  end

end
puts ans


a = gets.to_i

ml = gets.split.map(&:to_i)
mx = 10**18

res = 1
ml.each do |i|
  if ml.include?(0)
    res = 0
    break
  end
  res *= i
  res > mx ? res = -1 : res
end
puts res

Score : 200 points

Problem Statement

Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.

However, if the result exceeds 10^{18}, print -1 instead.

Constraints

2 \leq N \leq 10^5

0 \leq A_i \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}.

Sample Input 1

2
1000000000 1000000000

Sample Output 1

1000000000000000000

We have 1000000000 \times 1000000000 = 1000000000000000000.

Sample Input 2

3
101 9901 999999000001

Sample Output 2

-1

We have 101 \times 9901 \times 999999000001 = 1000000000000000001, which exceeds 10^{18}, so we should print -1 instead.

Sample Input 3

31
4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0

Sample Output 3

0


n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
product = a[1]
if a.include?(0) then
    puts "0"
    exit
end
for i in 1..a.length-1 do
    product = product *  a[i]
    if product > 100000000000000000 then
        puts "-1"
        exit
    end
end
puts product


n = gets.to_i
line = gets.chomp.split(" ").map(&:to_i);

answer = 1

for i in 0 .. (line.length-1) do
	answer = answer * line[i]
	if answer > 1000000000000000000 then
		puts "-1"
		exit
	end
end

puts answer


n = gets.chomp.to_i
a = gets.chomp.split(' ').map(&:to_i)
sum = 1

#for i in 1..n do
# a[i] *= a[i+1]
# i += 1
#end

a.each{|num|
  sum *= num
}
if(sum > 10 ** 18)
  sum = -1
end

puts sum


def main(str)
  as = str.split("\n")[1].split(" ").map(&:to_i)
  as.inject do |m, x|
    r = m * x
    break -1 if r > 10 ** 18
    r
  end
end

unless ENV["TEST"]
  puts(main($stdin.read.chomp))
  exit(0)
end

require 'minitest/autorun'

class TestA < Minitest::Test
  def test_main
    assert_equal(1000000000000000000, main("2
1000000000 1000000000"))
    # assert_equal("", main(""))
    # assert_equal("", main(""))
  end
end


n=gets
an=gets.split(" ")
an=an.map{|n| n.to_i}

sum=1
for a in an
  sum*=a
  if sum > 1000000000000000000
    p -1
    exit
  end
end
p sum


count = gets.chomp.to_i
input_line = gets.split(' ').map(&:to_i)

if input_line.include?(0)
  puts 0
  exit
end

total = 1
input_line.each do |num|
  if total*num > 1000000000000000000
    puts -1
    exit
  else
    total *= num
  end
end
puts total


N = gets.to_i
A = gets.chomp.split.map(&:to_i).sort
ans = A[0]

(1..N-1).each do |i|
  ans *= A[i]
  break if ans > 10**18 || ans ==0
end

if ans > 10**18
  puts -1
else
  puts ans
end


_n = gets.to_i
a= gets.split.map(&:to_i).inject(:*)
if a<=10**18
  puts(ans)
else
  puts(-1)
end


a = gets.chomp.to_i
ary = gets.chomp.split(" ").map(&:to_i).sort

if ary.first == 0
  puts 0
else
  t = 1
  ary.each do |v|
    t *= v
    if t > (10 ** 18)
      t = -1
      break
    end
  end
  puts t
end


a = gets.split.map(&:to_i).inject(:*)
a = -1 if a > 10**18
puts a


_ = gets
a = gets.chomp.split.map(&:to_i)
res = 1
a.each do |x|
  res *= x
  if res > 10 ** 18
    res = -1
    break
  elsif res == 0
    break
  end
end
puts res


n = gets.to_s.to_i
a = gets.to_s.split

if a.include?('0')
  puts 0
  exit
end

a = a.split.map{|e|e.to_i}
ans = 1
inf = 10 ** 18
a.each do |t|
  ans *= t
  if ans > inf
    puts "-1"
    exit
  end
end

puts ans


a = gets.to_i
line = gets.split(' ').map(&:to_i)
if line.include?(0)
  puts 0
else
  i= 1
  for n in 0..a-1 do
    i *= line[n]
    if i > 1000000000000000000
    	i = -1
    	puts i
      	exit
  	end
  end
  puts i
end


lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]
mal = lines[1].sort
limit = 10 ** 18

ans = 1
for i in 1..N do
  ans *= mal[i-1]
  if ans > limit then
    ans = -1
    break
  end
end

print ans


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

answer = a.reduce do |result, item|
  result *= item

  break -1 if result > 10 ** 18

  result
end

print(answer)


N = gets.to_i
a = []
a = gets.split.map(&:to_i)

ans = 1
N.times do |i|
  ans = ans * a[i]
  if ans == 0
    puts 0
    exit
  end
end
if ans > 10**18
  puts -1
  exit
end

puts ans


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

result=m[0]

for i in 0..n-1
if m[i]==0
p 0
exit
end
result=m[i]*result

end

if result>1.0*10**18
puts -1
exit
end
p result


#input of int(split by space)
def get_i()
  return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
  return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
  return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
  return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
  return bool ? y : n
end
#create of array
def array(size1,init=nil,size2=-1)
  if size2==-1
    return Array.new(size1){init}
  else
    return Array.new(size2){Array.new(size1){init}}
  end
end

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

def min(a,b)
    return a>b ? b : a
end

INF=Float::INFINITY

N=gets.to_i
A=get_i
ans=1
if A.include?(0)
    puts 0
    exit
end
A.each do|a|
    ans*=a
    if ans>10**18
        puts "-1"
        exit
    end
end
puts ans


gets
puts gets.split.map(&:to_i).inject(1){|acc,it|
    val = acc * it
    if val > 10 ** 18
        -1
    else
        val
    end
}


n = gets.to_i
a = gets.split.map(&:to_i)
r = a.inject(:*)
puts r > 10 ** 18 ? -1 : r


_ = gets.to_i
a = gets.split.map(&:to_i)
if a.include?(0)
    puts 0
    exit
end
p = 1
a.each do |aa|
    p *= aa
    if p > 10**18
        p = -1
        break
    end
end
puts p


_ = gets.to_i
a = gets.split.map(&:to_i)
if a.include?(0)
    puts 0
    exit
end
p = 1
a.each do |aa|
    p *= aa
    if p > 10*18
        p = -1
        break
    end
end
puts p


gets
ans = 1
gets.split.map(&:to_i).sort.each do |a|
    ans *= a
    if ans > 10**18
        p -1
        exit
    end
end
p ans


n = gets.to_i
a = gets.chomp.split
mul = 1
n.times do |i|
    mul *= a[i].to_i
    break if mul > 10 ** 18
end
puts mul > 10 ** 18 ? -1 : mul


n=gets.to_i
a=gets.split.map &:to_i
z=1
a.map{|x|
z*=x
break if z>10**18
}
p a.index(0)?0:z>10**18?-1:z


gets
a = gets.split.map(&:to_i).inject(:*)
puts a > 10 ** 18 ? -1 : a


n = gets.to_i
a = gets.split.map(&:to_i)
b = a.inject(:*)
if b > 10 ** 18
  puts '-1'
else
  puts b
end


require 'bigdecimal'
A, B = gets.strip.split.map(&:to_s)
puts (BigDecimal(A)*BigDecimal(B)).floor

Score : 300 points

Problem Statement

Compute A \times B, truncate its fractional part, and print the result as an integer.

Constraints

0 \leq A \leq 10^{15}

0 \leq B < 10

A is an integer.

B is a number with two digits after the decimal point.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the answer as an integer.

Sample Input 1

198 1.10

Sample Output 1

217

We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217.

Sample Input 2

1 0.01

Sample Output 2

0

Sample Input 3

1000000000000000 9.99

Sample Output 3

9990000000000000


s = gets.strip.split.map(&:to_i)
A = s[0].to_i
B = 100*s[1].to_i
puts ((A*B).to_f/100).floor


require 'bigdecimal'
input = STDIN
numbers = input.gets.split(' ')
puts (BigDecimal(numbers[0]) * BigDecimal(numbers[1])).to_i


A, B = gets.to_s.split(' ').map(&:to_f)

puts A * B.floor


a,b = gets.chomp.split(" ")
a = a.to_i
b = b.gsub(".", "").to_i

result = (a * b).to_s
if result.length < 3
  puts 0
else
  puts result[0..-3]
end


a, b = gets.split
a = a.chars.map(&:to_i)
b = ((b.to_f)*100).to_i.to_s.chars.map(&:to_i)
ans = Array.new(a.size + 3, 0)
a.size.times do |i| 3.times do |j|
  ans[i + j + 1] += a[i] * b[j]
end end
(ans.size - 1).downto(1) do |i|
  ans[i - 1] += ans[i] / 10
  ans[i] = ans[i] % 10
end
puts ans.join.to_i / 100


require "bigdecimal"

a, b = gets.to_s.split.map{|t| BigDecimal(t) }
puts ( a * b ).floor


a, b = gets.split.map(&:to_f)
puts (a * b).floor


a, b = gets.to_s.split.map{|t| t.to_r }

puts (a * b).floor


a, b = gets.to_s.split.map{|t| t.to_f }
puts (a * (b*1000).round / 1000).to_i


a, b = gets.split
puts a.to_i * (b.to_f * 100 + 0.1).floor / 100


line=gets.split(' ')
a=line[0].to_i
/(\d+)\.(\d+)/.match(line[1])
b_int=$1.to_i
b_dec=$2.to_i
puts a*(b_int*100+b_dec)/100


IN = gets.split
A = IN[0].to_i
B = ((IN[1].to_f * 100)).to_i
mul = ((B*A).to_i) / 100

puts mul


require "bigdecimal"

a,b = gets.split
puts (BigDecimal(a) * BitDecimal(b)).floor


all = gets.chomp
n1 = all.split[0].to_f
n2 = all.split[1].to_f
puts (n1*n2).to_i


a, b = gets.chomp.split(" ")
a = a.to_i
b = b.to_f
puts (a * b).floor


a, b = gets.chomp.split(" ")
a = a.to_i
b = b.to_f
mul = a * b
mul = mul.floor
print mul


x, y = gets.chomp.split
puts (x.to_i * y.to_f).round


array = gets.split(' ')

a = array[0].to_i
b = array[1].to_f

sum = a * b

sum = sum.to_i

puts sum


a,b=gets.chomp.split
a = a.to_i

puts a * b.delete(".").to_i / 100


N, M = gets.chomp.split.map(&:to_f)
N.freeze
M.freeze

ans = N.to_f * M.to_f

puts ans.floor


a1,b1 = gets.strip.split(" ")
a = a1.to_i
b = b1.to_f
if a == 0
  puts 0
elsif b ==0
  puts 0
else
  puts (a*b).to_i
end


a,b = gets.split.map(&:to_f)
puts ((b*100)*a).to_i / 100


#input of int(split by space)
def get_i()
  return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
  return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
  return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
  return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
  return bool ? y : n
end
#create of array
def array(size1,init=nil,size2=-1)
  if size2==-1
    return Array.new(size1){init}
  else
    return Array.new(size2){Array.new(size1){init}}
  end
end

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

def min(a,b)
    return a>b ? b : a
end

INF=Float::INFINITY

a,b=get_f
a=a.to_i
b=(b*1000).to_i
puts ((a*b)/1000).floor


a, b = gets.split(" ")
ans = a.to_i * b.to_f
puts ans
puts ans.floor


a,b = gets.chomp.split(' ').map(&:to_f)
puts (a * b).floor


a,b=gets.chomp.split
a = a.to_i
b = ((b.to_f)*100).to_i
puts (a*b/100).to_i


A, B = ARGF.gets.chomp.split.collect {|el| el.to_f}

puts (A * B).to_i


A, B = gets.split.map(&:to_f)
puts (A * B).to_i


a_as_str, b_as_str = gets.chomp.split(/ /)
a = a_as_str.to_i
b = b_as_str.to_f

puts (a * (b * 100).to_i) / 100


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

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

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

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

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

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

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

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

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

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

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

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end
a,b = inpf
a = a.to_i
b = (b*100).to_i
p (a*b)/100


a, b = gets.chomp.split(" ").map(&:to_f)
puts (a*b).floor


a,b = gets.split.map(&:to_f)
puts (a*b).to_i


a, b = gets.split
a = a.to_i
b = b.to_f
puts (a*b).to_i


Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2


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

route = []
s = []
i = 1
l = 0

k.times do |j|
  i = a[i-1]
  if route.include?(i)
    if s.include?(i)
      t = (k - l - 1) % s.length
      print(t, "\n")
      print(s, "\n")
      route << s[t]
      break
    else
      l = j if l == 0
      s << i
      route << i
    end
  else
    route << i
  end
end

print route.last


N, K = gets.split(" ").map(&:to_i)
A = gets.split(" ").map(&:to_i)

cs = Array.new(N + 1, 0)
i, x, y = 1, [], []
# xは初めて訪れた所を記録している→そうステップ数　= x.size
# yは一回訪れたところを記録する→周期　= y.size

until cs[i] == 2
    (cs[i].zero? ? x : y) << i
    cs[i] += 1
    i = A[i - 1]
end

puts K < x.size ? x[K] : y[(K - x.size) % (y.size)]


(N, K), As = readlines.map{_1.split.map(&:to_i)}

cs = Array.new(N + 1, 0)
i, x, y = 1, [], []
until cs[i] == 2
  (cs[i].zero? ? x : y) << i
  cs[i] += 1
  i = As[i - 1]
end
puts K <= x.size ? x[K - 1] : y[(K - x.size)%(y.size)]


n,k=gets.split.map(&:to_i)
as=gets.split.map(&:to_i)
check=[-1]*n
check[0]=0
i=0
to=0
d=0
while true
  i+=1
  to=as[to]-1
  if i==k
    puts to+1
    exit
  end
  if check[to]>=0
    d=i-to
    break
  else
    check[to]=i
  end
end
m=(k-check[to])%d
puts check.index(to+m)+1


nums=gets.strip.split(" ").map do |i|
  i.to_i
end
n=nums[0]
k=nums[1]
s=nums=gets.strip.split(" ").map do |i|
  i.to_i
end
now=1
tele_num=0
a = Array.new(n,nil)
a[0] = 0
flag=false
#puts "tele_num #{tele_num} now #{now}"
while tele_num < k
  next_pos = s[now-1]
  tele_num+=1
  #puts "tele_num #{tele_num} next_pos #{next_pos}"
  if a[next_pos].nil? || flag
    a[next_pos] = tele_num
  else
    #puts "tele_numff #{tele_num}"
    #puts "next_pos #{a[next_pos]}"
    loop_num = tele_num - a[next_pos]
    #puts "loop_num #{loop_num}"
    t=((k - tele_num) / loop_num).to_i

    tele_num += (t*loop_num)
    flag=true
  end
  now = next_pos
end
puts now


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

for i in 0...n
    a[i] -= 1
end

visited = Array.new(n, false)
order = []

order.push(0)
len = nil
d1 = nil
for i in 1..n
    nxt = a[order[i-1]]
    p nxt
    if visited[nxt]
        len = i
        for j in 0...n
            if nxt == order[j]
                d1 = j
                break
            end
        end
        break
    else
        order.push(nxt)
        visited[nxt] = true
    end
end

if len
    if len == 1
        #p "A"
        puts order[0] + 1
    else
        d2 = len - d1
        #p "B len:#{len} d1:#{d1} d2:#{d2}"
        kk = (k - d1) % d2
        puts order[d1 + kk] + 1
    end
else
    #p "C"
    puts order[k-1] + 1
end


n,k = gets.split(' ').map(&:to_i)
terepos = gets.split(' ').map(&:to_i)
next_list = [1]
while next_list.length <= [k,200000].min
  # result = next_list.index(terepos[next_list[-1] - 1])
  # if result
  #   roop_index = result
  #   break
  # else
    next_list << terepos[next_list[-1] - 1]
  # end
end
roop_length = next_list.uniq.size
roop_start = next_list.index(next_list[roop_length])
# puts("-------------")
# puts(roop_start)
# puts(roop_length)
# puts("-------------")

if k == next_list.size
  puts(next_list[-1])
else
  puts(next_list[((k + 1 - roop_start) % (roop_length - roop_start) + (roop_length - roop_start) - 1) % (roop_length - roop_start) + roop_start])
end


lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

n = lines[0][0]
k = lines[0][1]
go_to = lines[1]

current_town = 1
travel_root = []
visited = []
for i in 1..n do
  visited[i-1] = false
end
for i in 1..n+1 do
  travel_root.push(current_town)
  if visited[current_town - 1] then
    first_visit = travel_root.index(current_town)
    second_visit = i - 1
    loop_num = second_visit - first_visit
    break
  end
  visited[current_town - 1] = true
  current_town = go_to[current_town - 1]
end

if first_visit == 0 then
  print travel_root[k % loop_num]
elsif k <= first_visit then
  print travel_root[k]
else
  num = (k - first_visit)
  print travel_root[(num % loop_num) + first_visit]
end


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

tl = Array.new(n,0)
tl[0] = 1
nxt = a[0]
for i in 1..(n-1)
  tl[i] = nxt
  nxt = a[nxt-1]
end
ck = Array.new(n+1,0)
en = n-1
for i in 0..(n-1)
  if ck[tl[i]] == 0
    ck[tl[i]] += 1
  else
    lps = tl[i]
    en = i-1
  end
end

mg = 0
if en != n-1
  for i in 0..en
    if tl[i] == lps
      break
    else
      mg += 1
    end
  end
end

if k <= n-1
  puts tl[k]
else
  puts tl[mg + (k-mg) % (en+1-mg)]
end


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

hash = { 1 => 0}
keiro = [1]
current = 1
nex = nil
count = 0
while true do
  nex = a[current-1]
  keiro.push(nex)
  break unless hash[nex].nil?
  count += 1
  hash[nex] = count
  current = nex
end

if keiro.size - 1 >= k
  puts keiro[k]
  exit
end

start = hash[nex]
loop = keiro[start..-1]

before_loop = keiro.size - loop.size
k = k - before_loop
k = k % (loop.size - 1)
puts loop[k]


n,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = Array.new(n, 0)
b[0] = 1
nex = 0
roop = 0
offset = 0
ans = 0
k.times do |i|
    if b[a[nex]-1] == 0
        b[a[nex]-1] = i+2
        nex = a[nex]-1
    else
        roop = i - b[a[nex]-1] + 2
        offset = b[a[nex]-1]-1
        rem = (k - offset)%roop
        ans = b.index(b[a[nex]-1]+rem)+1
        break
    end
    if i == k
        ans = nex+1
    end
end
puts ans


n,k = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i)

ofs = []
line = [1]
hash = {}
hash[1] = 0
piv = 1

n.times do |c|
  piv = a[piv-1]
  if line.include?(piv)
    ofs = line.take(hash[piv])
    line = line.drop(hash[piv])
    break
  end
  hash[piv] = c+1
  line << piv
end

if k < ofs.length
  puts("#{ofs[k]}")
else
  k -= ofs.length
  puts("#{line[k%line.length]}")
end


require 'pp'
$DEBUG ? define_method(:dpp){|e|pp e} : define_method(:dpp){|e|}

# 空白区切の入力値を数値の配列で返却する
def gets_i_list()
  gets.chomp.split(" ").map(&:to_i)
end
N, K = gets_i_list
a_list = [0]
a_list += gets_i_list

to = a_list[1]
route = [1]
count = 0
K.times do |i|
  if route.include?(to)
    remain_count = (K - route.size)
    rloop = route.slice(route.index(to), route.size)
    puts rloop[remain_count % rloop.size]
    exit
  end
  route.push(to)
  to = a_list[to]
end
puts route.last


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

i = 1
h = Hash.new
a = []
x = []
y = []
while true do
  index = h[i]
  if index.nil?
    h[i] = a.length
    a << i
    i = t[i - 1]
  else
    x = a[0, index]
    y = a[index, a.length - index]
    break
  end
end

if x.length > k
  p x[k]
else
  z = (k - x.length) % y.length
  p y[z]
end


n, k = gets.split.map!(&:to_i)
a    = gets.split.map!(&:to_i).unshift(0)

x = 1
a1 = 1
a2 = a[a1]
while a1 != a2
  x += 1
  a1 = a[a1]
  a2 = a[a[a2]]
end

k %= x

puts k.times.inject(1) { |ai, *| a[ai] }


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

i = 1
a = []
x = []
y = []
while true do
  index = a.find_index i
  if index.nil?
    a << i
    i = t[i - 1]
  else
    x = a[0, index]
    y = a[index, a.length - index]
    break
  end
end

if x.length > k
  p x[k]
else
  z = (k - x.length) % y.length
  p y[z]
end


require 'set'
N, K = gets.split.map &:to_i
A = gets.split.map &:to_i
seq = [1]
set = Set.new([1])
idx = nil
while true
    next_one = A[seq[-1] - 1]
    seq << next_one
    added = set.add?(next_one)
    if !added
        idx = seq.find_index(next_one)
        break
    end
end
if K < seq.size
    p seq[K]
else
    mod = (K - idx) % (seq.size - idx - 1)
    p seq[idx + mod]
end


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

x = 1
c = Array.new(n+1)
c[1] = 0

while k > 0
    y = a[x-1]

    if c[y]
        k -= 1
        k %= c[x] + 1 - c[y]
        x = a[x-1]
        while k > 0
            x = a[x-1]
            k -= 1
        end
        break
    end

    c[y] = c[x] + 1
    x = y
    k -= 1
end

puts x


A = gets.chomp.to_i
B = gets.chomp.to_i
C = gets.chomp.to_i
D = gets.chomp.to_i

BC = C/B.to_f
DA = A/D.to_f

if BC <= DA
    puts('Yes')
else
    puts('No')
end

Score : 200 points

Problem Statement

Takahashi and Aoki will have a battle using their monsters.

The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.

The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes 0 or below. The person with the monster whose health becomes 0 or below loses, and the other person wins.

If Takahashi will win, print Yes; if he will lose, print No.

Constraints

1 \leq A,B,C,D \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

If Takahashi will win, print Yes; if he will lose, print No.

Sample Input 1

10 9 10 10

Sample Output 1

No

First, Takahashi's monster attacks Aoki's monster, whose health is now 10-9=1.

Next, Aoki's monster attacks Takahashi's monster, whose health is now 10-10=0.

Takahashi's monster is the first to have 0 or less health, so Takahashi loses.

Sample Input 2

46 4 40 5

Sample Output 2

Yes


a,b,c,d = gets.chomp.split.map(&:to_i)

if (c / d).ceil < (a /d).ceil
  puts "Yes"
else
  puts "No"
end


a,b,c,d = gets.chomp.split.map(&:to_i)
if (a/d.to_f) >= (c/b.to_f)
    puts 'Yes'
else puts 'No'
end


a,b,c,d = gets.chomp.split.map(&:to_i)
if (a/d.to_f) < (c/b.to_f)
    puts 'No'
else puts 'Yes'
end


A, B, C, D = gets.split.map(&:to_i)

a = C - B
b = A - D

while b > 1 do
  a = a - B
  b = b - D
end

if b == 0
  puts "No"
elsif b < 0
  puts "No"
else
  puts "Yes"
end


line = gets.split(' ').map(&:to_i)

t = line[0..1]
a = line[2..3]

winner = 0
while true do
  if winner == 0 || winner % 2 == 0
    break if (a[0] - t[1] <= 0)
    a[0] -= t[1]
  else
    break if (t[0] - a[1] <= 0)
    t[0] -= a[1]
  end
  winner += 1
end

if winner == 0 || winner % 2 == 0
  puts "Yes"
else
  puts "No"
end


def count(hp,bp)
  if(hp%bp==0)
    return hp/bp+1
  end
  return hp/bp
end

A,B,C,D = gets.split()
puts(count(A.to_i(),D.to_i()))
puts(count(C.to_i(),B.to_i()))
if(count(A.to_i(),D.to_i())<=count(C.to_i(),B.to_i()))
  puts('Yes')
else
  puts('No')
end


a,b,c,d=gets.split.map &:to_f
puts (c/b).ceil<=(a/d).ceil ? "Yes" : "No"


a, b, c, d = gets.split.map(&:to_i)
count = 1
while a > 0 && c > 0
  if count.odd?
    c -= b
  else
    a -= d
  end
  count += 1
end
if a <= 0
  puts "No"
else
  puts "Yes"
end


a,b,c,d=gets.split.map &:to_i
# 耐えられる回数は高橋がA/D
# 青木がC/B
if (a/d).ceil<(c/b).ceil then
  puts "Yes"
else
  puts "No"
end


S = gets.chomp

n, x = S.length, 0
(0 ... n - 3).each do |i|
  (i + 3 ... n).each do |j|
    x += 1 if S[i .. j].to_i % 2019 == 0
  end
end
puts x

Score : 400 points

Problem Statement

Given is a string S consisting of digits from 1 through 9.

Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:

Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

Constraints

1 ≤ |S| ≤ 200000

S is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.


ss = gets.chomp
ary = num = ss.length
result = []
num.times do |i|
  ary.times do |j|
    if j > 2
      if ss[i..(j+i)].to_i % 2019 == 0
        result.push([i,(j+i)])
      end
    end
  end
  ary = ss[(i+1)..num].length
end
puts result.length


s = gets.chomp
n = s.size
a = []
for i in 0..(n-1)
  a << (s.slice(i..(n-1)).to_i)%2019
end
a << 0
a.sort!
ans = 0
y = 1
m = a.size
while true
  if m < 2
    ans += y*(y-1)/2
    break
  elsif a[0] == a[1]
    y += 1
    a.shift
    m -= 1
  else
    ans += y*(y-1)/2
    m -= 1
    y = 1
    a.shift
  end
end
puts ans


s = gets.chomp
tmp = sum = 0
h = Hash.new(0)
h[0] += 1

s.size.times do |i|
  tmp += s[-1 - i].to_i * 10**i
  h[tmp % 2019] += 1
end

h.values.each { |i| sum += i * (i - 1) }

puts sum / 2


s = gets.chomp
tmp = sum = 0
cum = [tmp]
h = Hash.new(0)

s.size.times do |i|
  tmp += s[-1 - i].to_i * 10**i
  cum << tmp
end

cum.each { |i| h[i % 2019] += 1 }
h.values.each { |i| sum += i * (i - 1) }

puts sum / 2


# n = gets.to_s.to_i
m = 2019
s = gets.to_s.chomp.bytes

ans = 0
# p '0'.ord #=> 48
if false # m == 2 || m == 5

  n.times{ |i| (s[i] - 48 )%m == 0 && ans+=(i+1) }

else

  h = Hash.new(0)
  h[0] = 1

  cur = 0
  p10 = 1

  s.reverse_each do |c|
    cur = ( cur + ( c - 48 ) * p10 ) % m
    ans += h[cur]
    h[cur] += 1
    p10 = p10 * 10 % m
  end
end

puts ans


S = gets.chomp.split("").map &:to_i
N = S.size
Mod = 2019
a = 0
q = 1
A = S.reverse!.map{ |s|
  a = (a + s * q) % Mod
  q = q * 10 % Mod
  a
}
A.reverse!
A << 0
cnt = Array.new(2019, 0)
ans = 0
(0...A.size-1).reverse_each{ |i|
  a = A[i]
  b = A[i+1]
  ans += cnt[a]
  cnt[b] += 1
}
p ans


s=gets.chomp
mods=[0]*2019
digit=1
sum=0

s.reverse.chars do |ch|
  sum=(sum+digit*ch.to_i)%2019
  mods[sum]+=1
  digit=(digit*10)%2019
end

puts  mods.sum{|m| m*(m-1)/2}+mods[0]


s = gets.chomp!
mods = Array.new(s.size + 1, 0)
(mods.size - 2).downto(0){|i|
	mods[i] = (mods[i + 1] + s[i].to_i * (10 ** (s.size - i - 1))) % 2019;
}
p mods
puts 2019.times.sum{|i| m = mods.count(i); m * (m - 1) / 2}


S=gets.chomp

ret = 0
i = S.length-5
j = S.length-1
while 0 <= j
  if i < 0
    j -= 1
    i = j-4
  elsif S[i..j].to_i % 2019 == 0
    ret += 1
    j -= 1
    i = j-4
  else
    i -= 1
  end
end

puts ret


s = gets.chop
n=s.length()
result=0
lookup = Array.new(100)
for i in 0..99 do
    i1 = i*2019
    lookup[i1%100]=i1
end
for j in 4..n do
    s1=s[0,j]
    x=s1.to_i
    sum=0
    while 2019<=x
        i1=x%100
        x=x-lookup[i1]
        if x%10000 == 0
            result += 1
            x=x/10000
        else
            x=x/100
        end
    end
end
puts result


ss = gets.chomp.chars
res = 0
str = ''
ss.each do |s|
  str += s
  num = str.to_i
  res += 1 if num % 2019 == 0 && num <= 200000 && num > 0 && !str.empty?
  str.size.times do |i|
    t = str.slice(i+1..-1)
    n = t.to_i
    res += 1 if n % 2019 == 0 && n <= 200000 && n > 0 && !t.empty?
  end
end
puts res


s = gets.strip
c = 0
(0...s.length).each{|i|
  (i...s.length).each{|j|
    c += 1 if s[i..j].to_i % 2019 == 0
  }
}
puts c


s = gets.chomp!
count = 0

(1..100).each do |n|
	word = (2019 * n).to_s
	count += s.scan(/(?=#{word})/).size
end

puts count


#!/usr/bin/env ruby

attrs = Array.new
while line = $stdin.gets
  attrs << line.chomp.split
end

S = attrs[0][0]
cnt = 0
(0..(S.length-4)).each do |i|
  ((i+3)..(S.length-1)).each do |j|\
    cnt += 1 if (S[i..j].to_i % 2019 == 0)
  end
end
puts cnt


# Studying https://img.atcoder.jp/abc164/editorial.pdf

# Inputs

N,M,S = gets.split.map(&:to_i)
E,amax = Hash.new{|h,k| h[k]={} }, 0
M.times.map{
	u,v,a,b = gets.split.map(&:to_i)
	E[u-1][v-1] = E[v-1][u-1] = [a,b]
	amax = a if amax < a
}
X = N.times.map{ gets.split.map(&:to_i) }

# Tools

class PQ
	def initialize
		@h = [] # min-heap
	end

	def enq(v)
		@h.push(v)
		up_heap
	end

	def deq
		max, last = @h[0], @h.pop
		unless @h.empty?
			@h[0] = last
			dn_heap
		end
		return max
	end

private
	def up_heap
		i, up = @h.size-1, @h[-1]
		while 0 <= (iP = (i-1)/2)
			break unless up < @h[iP]
			@h[i], i = @h[iP], iP
		end
		@h[i] = up
	end

	def dn_heap
		i, dn, size = 0, @h[0], @h.size
		while (iC = 2*i+1) < size
			iC += 1 if iC+1 < size and @h[iC+1] < @h[iC]
			break unless @h[iC] < dn
			@h[i], i = @h[iC], iC
		end
		@h[i] = dn
	end
end

R = lambda{|t,s,u|
	next t<<32 | [s,(N-1)*amax].min<<16 | u
}
Я = lambda{|r|
	next r>>32, r>>16&4095, r&63
}

# Main

n,T,２ = 0, [nil]*N, [-1]*N
Q = PQ.new; Q.enq R[0,S,0]
while k = Q.deq
	t,s,u = Я[k]

	if T[u].nil? # first arrived.
		n, T[u] = n+1, t
		break if n == N # completed.
	end

	next if s < ２[u] # 銭なしの再訪に用なし
	２[u] = s

	c,d = X[u]
	Q.enq R[t+d,s+c,u]

	E[u].each{|v,(a,b)|
		Q.enq R[t+b,s-a,v] if a<=s
	}
end

# Output

T.shift
p *T

Score : 500 points

Problem Statement

There are N cities numbered 1 to N, connected by M railroads.

You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.

The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes.
You cannot use gold coins to pay the fare.

There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin.
The transaction takes D_i minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.

For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq 100

0 \leq S \leq 10^9

1 \leq A_i \leq 50

1 \leq B_i,C_i,D_i \leq 10^9

1 \leq U_i < V_i \leq N

There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).

Each city t=2,...,N can be reached from City 1 with some number of railroads.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N

Output

For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.

Sample Input 1

3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5

Sample Output 1

2
14

The railway network in this input is shown in the figure below.

In this figure, each city is labeled as follows:

The first line: the ID number i of the city (i for City i)

The second line: C_i / D_i

Similarly, each railroad is labeled as follows:

The first line: the ID number i of the railroad (i for the i-th railroad in input)

The second line: A_i / B_i

You can travel from City 1 to City 2 in 2 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

You can travel from City 1 to City 3 in 14 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 6 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Sample Input 2

4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4

Sample Output 2

5
5
7

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 4 in 7 minutes, as follows:

At the exchange counter in City 1, exchange 2 gold coins for 6 silver coins in 2 minutes.

Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.

Use the 4-th railroad to move from City 3 to City 4 in 1 minutes.

Sample Input 3

6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1

Sample Output 3

1
9003
14606
16510
16576

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 6 in 16576 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 9000 minutes.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

At the exchange counter in City 3, exchange 8 gold coins for 8 silver coins in 5600 minutes.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

Use the 3-rd railroad to move from City 2 to City 4 in 1 minute.

At the exchange counter in City 4, exchange 19 gold coins for 19 silver coins in 1900 minutes.

Use the 3-rd railroad to move from City 4 to City 2 in 1 minute.

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

Use the 4-th railroad to move from City 3 to City 5 in 1 minute.

At the exchange counter in City 5, exchange 63 gold coins for 63 silver coins in 63 minutes.

Use the 4-th railroad to move from City 5 to City 3 in 1 minute.

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 5-th railroad to move from City 1 to City 6 in 1 minute.

Sample Input 4

4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7

Sample Output 4

1
3
5

The railway network in this input is shown in the figure below:

Sample Input 5

2 1 0
1 2 1 1
1 1000000000
1 1

Sample Output 5

1000000001

The railway network in this input is shown in the figure below:

You can travel from City 1 to City 2 in 1000000001 minutes, as follows:

At the exchange counter in City 1, exchange 1 gold coin for 1 silver coin in 1000000000 minutes.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.