結果
問題 | No.1665 quotient replace |
ユーザー |
![]() |
提出日時 | 2021-09-03 21:30:21 |
言語 | Crystal (1.14.0) |
結果 |
AC
|
実行時間 | 2,167 ms / 3,000 ms |
コード長 | 20,339 bytes |
コンパイル時間 | 12,227 ms |
コンパイル使用メモリ | 300,280 KB |
実行使用メモリ | 77,676 KB |
最終ジャッジ日時 | 2024-12-15 10:12:56 |
合計ジャッジ時間 | 39,971 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 41 |
ソースコード
# require "/template"# require "./tuple/times"struct Tupledef times(&block) : Nil{% begin %}{% for i in 0...@type.size %}{% if @type[i].has_method?(:each) %}self[{{i}}].each do |i{{i}}|{% else %}self[{{i}}].times do |i{{i}}|{% end %}{% end %}yield({% for i in 0...@type.size %} i{{i}}, {% end %}){% for i in 0...@type.size %} end {% end %}{% end %}endprivate class TimesIterator(T)include Iterator(T)def initialize(@n : T)tuple = {% begin %}{ {% for i in 0...T.size %} T[{{i}}].zero, {% end %} }{% end %}@index = tuple.as(T)@first = trueenddef nextif @first@first = falsereturn @indexend{% begin %}{%type = @type.type_vars[0]size = type.size%}{% for i in 1..size %}if @index[{{size - i}}] < @n[{{size - i}}] - 1@index = {{% for j in 0...size %}{% if j < size - i %}@index[{{j}}],{% elsif j == size - i %}@index[{{j}}] + 1,{% else %}{{type[j]}}.zero,{% end %}{% end %}}return @indexend{% end %}stop{% end %}endenddef timesTimesIterator(self).new(self)endend# require "./comparable/min_max"module Comparable(T)def min(x : T)self > x ? x : selfenddef max(x : T)self < x ? x : selfendend# require "./array/new"class Arraydef self.new(sizes : Tuple(*T), initial_value) forall T{% begin %}{% for i in 0...T.size %} Array.new(sizes[{{i}}]) { {% end %}initial_value{% for i in 0...T.size %} } {% end %}{% end %}enddef self.new(sizes : Tuple(*T), &block) forall T{% begin %}{% for i in 0...T.size %} Array.new(sizes[{{i}}]) { |index{{i}}| {% end %}yield({% for i in 0...T.size %} index{{i}}, {% end %}){% for i in 0...T.size %} } {% end %}{% end %}endend# require "./array/change"class Array(T)def chmin(i : Int, value : T)(self[i] > value).tap do |f|self[i] = value if fendendprotected def chmin(i : Int, *indexes, value)self[i].chmin(*indexes, value: value)enddef chmin(indexes : Tuple, value)chmin(*indexes, value: value)enddef chmax(i : Int, value : T)(self[i] < value).tap do |f|self[i] = value if fendendprotected def chmax(i : Int, *indexes, value)self[i].chmax(*indexes, value: value)enddef chmax(indexes : Tuple, value)chmax(*indexes, value: value)endend# require "./scanner"# ### Specifications## ```plain# Inside input macro | Expanded code# -------------------------------------+---------------------------------------# Uppercase string: Int32, Int64, etc. | {}.new(Scanner.s)# s | Scanner.s# c | Scanner.c# Other lowercase string: i, i64, etc. | Scanner.s.to_{}# operator[]: type[size] | Array.new(input(size)) { input(type) }# Tuple literal: {t1, t2, t3} | {input(t1), input(t2), input(t3)}# Array literal: [t1, t2, t3] | [input(t1), input(t2), input(t3)]# Range literal: t1..t2 | input(t1)..input(t2)# If: cond ? t1 : t2 | cond ? input(t1) : input(t2)# Assign: target = value | target = input(value)# ```## ### Examples## Input:# ```plain# 5 3# foo bar# 1 2 3 4 5# ```# ```# n, m = input(Int32, Int64) # => {5, 10i64}# input(String, Char[m]) # => {"foo", ['b', 'a', 'r']}# input(Int32[n]) # => [1, 2, 3, 4, 5]# ```# ```# n, m = input(i, i64) # => {5, 10i64}# input(s, c[m]) # => {"foo", ['b', 'a', 'r']}# input(i[n]) # => [1, 2, 3, 4, 5]# ```## Input:# ```plain# 2 3# 1 2 3# 4 5 6# ```## ```# h, w = input(i, i) # => {2, 3}# input(i[h, w]) # => [[1, 2, 3], [4, 5, 6]]# ```# ```# input(i[i][i]) # => [[1, 2, 3], [4, 5, 6]]# ```## Input:# ```plain# 5 3# 3 1 4 2 5# 1 2# 2 3# 3 1# ```# ```# n, m = input(i, i) # => {5, 3}# input(i.pred[n]) # => [2, 0, 3, 1, 4]# input({i - 1, i - 1}[m]) # => [{0, 1}, {1, 2}, {2, 0}]# ```## Input:# ```plain# 3# 1 2# 2 2# 3 2# ```# ```# input({tmp = i, tmp == 1 ? i : i.pred}[i]) # => [{1, 2}, {2, 1}, {3, 1}]# ```## Input:# ```plain# 3# 1 2# 2 3# 3 1# ```# ```# n = input(i)# input_column({Int32, Int32}, n) # => {[1, 2, 3], [2, 3, 1]}# ```class Scannerprivate def self.skip_to_not_spacepeek = STDIN.peeknot_space = peek.index { |x| x != 32 && x != 10 } || peek.sizeSTDIN.skip(not_space)enddef self.cskip_to_not_spaceSTDIN.read_char.not_nil!enddef self.sskip_to_not_spacepeek = STDIN.peekif index = peek.index { |x| x == 32 || x == 10 }STDIN.skip(index + 1)return String.new(peek[0, index])endString.build do |buffer|loop dobuffer.write peekSTDIN.skip(peek.size)peek = STDIN.peekbreak if peek.empty?if index = peek.index { |x| x == 32 || x == 10 }buffer.write peek[0, index]STDIN.skip(index)breakendendendendendmacro internal_input(type, else_ast){% if Scanner.class.has_method?(type.id) %}Scanner.{{type.id}}{% elsif type.stringify == "String" %}Scanner.s{% elsif type.stringify == "Char" %}Scanner.c{% elsif type.stringify =~ /[A-Z][a-z0-9_]*/ %}{{type.id}}.new(Scanner.s){% elsif String.has_method?("to_#{type}".id) %}Scanner.s.to_{{type.id}}{% else %}{{else_ast}}{% end %}endmacro internal_input_array(type, args){% for i in 0...args.size %}%size{i} = input({{args[i]}}){% end %}{% begin %}{% for i in 0...args.size %} Array.new(%size{i}) { {% end %}input({{type.id}}){% for i in 0...args.size %} } {% end %}{% end %}endmacro input(type){% if type.is_a?(Call) %}{% if type.receiver.is_a?(Nop) %}internal_input({{type.name}}, {{type.name}}({% for argument in type.args %} input({{argument}}), {% end %})){% elsif type.name.stringify == "[]" %}internal_input_array({{type.receiver}}, {{type.args}}){% else %}input({{type.receiver}}).{{type.name.id}}({% for argument in type.args %} input({{argument}}), {% end %}) {{type.block}}{% end %}{% elsif type.is_a?(TupleLiteral) %}{ {% for i in 0...type.size %} input({{type[i]}}), {% end %} }{% elsif type.is_a?(ArrayLiteral) %}[ {% for i in 0...type.size %} input({{type[i]}}), {% end %} ]{% elsif type.is_a?(RangeLiteral) %}Range.new(input({{type.begin}}), input({{type.end}}), {{type.excludes_end?}}){% elsif type.is_a?(If) %}{{type.cond}} ? input({{type.then}}) : input({{type.else}}){% elsif type.is_a?(Assign) %}{{type.target}} = input({{type.value}}){% else %}internal_input({{type.id}}, {{type.id}}){% end %}endmacro input(*types){ {% for type in types %} input({{type}}), {% end %} }endmacro input_column(types, size){% for type, i in types %}%array{i} = Array({{type}}).new({{size}}){% end %}{{size}}.times do{% for type, i in types %}%array{i} << input({{type}}){% end %}end{ {% for type, i in types %} %array{i}, {% end %} }end# require "atcoder/Prime"# ac-library.cr by hakatashi https://github.com/google/ac-library.cr## Copyright 2021 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# require "./Math.cr"# ac-library.cr by hakatashi https://github.com/google/ac-library.cr## Copyright 2021 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.module AtCoder# Implements [ACL's Math library](https://atcoder.github.io/ac-library/master/document_en/math.html)module Mathdef self.extended_gcd(a, b)last_remainder, remainder = a.abs, b.absx, last_x, y, last_y = 0_i64, 1_i64, 1_i64, 0_i64while remainder != 0new_last_remainder = remainderquotient, remainder = last_remainder.divmod(remainder)last_remainder = new_last_remainderx, last_x = last_x - quotient * x, xy, last_y = last_y - quotient * y, yendreturn last_remainder, last_x * (a < 0 ? -1 : 1)end# Implements atcoder::inv_mod(value, modulo).def self.inv_mod(value, modulo)gcd, inv = extended_gcd(value, modulo)if gcd != 1raise ArgumentError.new("#{value} and #{modulo} are not coprime")endinv % moduloend# Simplified AtCoder::Math.pow_mod with support of Int64def self.pow_mod(base, exponent, modulo)if exponent == 0return base.class.zero + 1endif base == 0return baseendb = exponent > 0 ? base : inv_mod(base, modulo)e = exponent.absret = 1_i64while e > 0if e % 2 == 1ret = mul_mod(ret, b, modulo)endb = mul_mod(b, b, modulo)e //= 2endretend# Caluculates a * b % mod without overflow detection@[AlwaysInline]def self.mul_mod(a : Int64, b : Int64, mod : Int64)if mod < Int32::MAXreturn a * b % modend# 31-bit widtha_high = (a >> 32).to_u64# 32-bit widtha_low = (a & 0xFFFFFFFF).to_u64# 31-bit widthb_high = (b >> 32).to_u64# 32-bit widthb_low = (b & 0xFFFFFFFF).to_u64# 31-bit + 32-bit + 1-bit = 64-bitc = a_high * b_low + b_high * a_lowc_high = c >> 32c_low = c & 0xFFFFFFFF# 31-bit + 31-bitres_high = a_high * b_high + c_high# 32-bit + 32-bitres_low = a_low * b_lowres_low_high = res_low >> 32res_low_low = res_low & 0xFFFFFFFF# Overflowif res_low_high + c_low >= 0x100000000res_high += 1endres_low = (((res_low_high + c_low) & 0xFFFFFFFF) << 32) | res_low_low(((res_high.to_i128 << 64) | res_low) % mod).to_i64end@[AlwaysInline]def self.mul_mod(a, b, mod)typeof(mod).new(a.to_i64 * b % mod)end# Implements atcoder::crt(remainders, modulos).def self.crt(remainders, modulos)raise ArgumentError.new unless remainders.size == modulos.sizetotal_modulo = 1_i64answer = 0_i64remainders.zip(modulos).each do |(remainder, modulo)|gcd, p = extended_gcd(total_modulo, modulo)if (remainder - answer) % gcd != 0return 0_i64, 0_i64endtmp = (remainder - answer) // gcd * p % (modulo // gcd)answer += total_modulo * tmptotal_modulo *= modulo // gcdendreturn answer % total_modulo, total_moduloend# Implements atcoder::floor_sum(n, m, a, b).def self.floor_sum(n, m, a, b)n, m, a, b = n.to_i64, m.to_i64, a.to_i64, b.to_i64res = 0_i64if a < 0a2 = a % mres -= n * (n - 1) // 2 * ((a2 - a) // m)a = a2endif b < 0b2 = b % mres -= n * ((b2 - b) // m)b = b2endres + floor_sum_unsigned(n, m, a, b)endprivate def self.floor_sum_unsigned(n, m, a, b)res = 0_i64loop doif a >= mres += n * (n - 1) // 2 * (a // m)a = a % mendif b >= mres += n * (b // m)b = b % mendy_max = a * n + bbreak if y_max < mn = y_max // mb = y_max % mm, a = a, mendresendendendmodule AtCoder# Implements [Ruby's Prime library](https://ruby-doc.com/stdlib/libdoc/prime/rdoc/Prime.html).## ```# AtCoder::Prime.first(7) # => [2, 3, 5, 7, 11, 13, 17]# ```module Primeextend selfinclude Enumerable(Int64)@@primes = [2_i64, 3_i64, 5_i64, 7_i64, 11_i64, 13_i64, 17_i64, 19_i64,23_i64, 29_i64, 31_i64, 37_i64, 41_i64, 43_i64, 47_i64,53_i64, 59_i64, 61_i64, 67_i64, 71_i64, 73_i64, 79_i64,83_i64, 89_i64, 97_i64, 101_i64,]def eachindex = 0loop doyield get_nth_prime(index)index += 1endenddef prime_division(value : Int)raise DivisionByZeroError.new if value == 0int = typeof(value)factors = [] of Tuple(typeof(value), typeof(value))if value < 0value = value.absfactors << {int.new(-1), int.new(1)}enduntil prime?(value) || value == 1factor = valueuntil prime?(factor)factor = find_factor(factor)endcount = 0while value % factor == 0value //= factorcount += 1endfactors << {int.new(factor), int.new(count)}endif value > 1factors << {value, int.new(1)}endfactors.sort_by! { |(factor, _)| factor }endprivate def find_factor(n : Int)# Factor of 4 cannot be discovered by Pollard's Rho with f(x) = x^x+1if n == 4typeof(n).new(2)elsepollard_rho(n).not_nil!endend# Get single factor by Pollard's Rho Algorithmprivate def pollard_rho(n : Int)typeof(n).new(1).upto(n) do |i|x = iy = pollard_random_f(x, n)loop dox = pollard_random_f(x, n)y = pollard_random_f(pollard_random_f(y, n), n)gcd = (x - y).gcd(n)if gcd == nbreakendif gcd != 1return gcdendendendendprivate def pollard_random_f(n : Int, mod : Int)(AtCoder::Math.mul_mod(n, n, mod) + 1) % modendprivate def extract_prime_division_base(prime_divisions_class : Array({T, T}).class) forall TTenddef int_from_prime_division(prime_divisions : Array({Int, Int}))int_class = extract_prime_division_base(prime_divisions.class)prime_divisions.reduce(int_class.new(1)) { |i, (factor, exponent)| i * factor ** exponent }enddef prime?(value : Int)# Obvious patternsreturn false if value < 2return true if value <= 3return false if value.even?return true if value < 9if value < 0xffffreturn false unless typeof(value).new(30).gcd(value % 30) == 17.step(by: 30, to: value) do |base|break if base * base > valueif {0, 4, 6, 10, 12, 16, 22, 24}.any? { |i| value % (base + i) == 0 }return falseendendreturn trueendmiller_rabin(value.to_i64)endprivate def miller_rabin(value)d = value - 1s = 0_i64until d.odd?d >>= 1s += 1endmiller_rabin_bases(value).each do |base|next if base == valuex = AtCoder::Math.pow_mod(base.to_i64, d, value)next if x == 1 || x == value - 1is_composite = s.times.all? dox = AtCoder::Math.mul_mod(x, x, value)x != value - 1endreturn false if is_compositeendtrueend# We can reduce time complexity of Miller-Rabin tests by testing against# predefined bases which is enough to test against primarity in the given range.# https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test# ameba:disable Metrics/CyclomaticComplexityprivate def miller_rabin_bases(value)casewhen value < 1_373_653_i64[2, 3]when value < 9_080_191_i64[31, 73]when value < 25_326_001_i64[2, 3, 5]when value < 3_215_031_751_i64[2, 3, 5, 7]when value < 4_759_123_141_i64[2, 7, 61]when value < 1_122_004_669_633_i64[2, 13, 23, 1662803]when value < 2_152_302_898_747_i64[2, 3, 5, 7, 11]when value < 3_474_749_660_383_i64[2, 3, 5, 7, 11, 13]when value < 341_550_071_728_321_i64[2, 3, 5, 7, 11, 13, 17]when value < 3_825_123_056_546_413_051_i64[2, 3, 5, 7, 11, 13, 17, 19, 23]else[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]endendprivate def get_nth_prime(n)while @@primes.size <= ngenerate_primesend@@primes[n]end# Doubles the size of the cached prime array and performs the# Sieve of Eratosthenes on it.private def generate_primesnew_primes_size = @@primes.size < 1_000_000 ? @@primes.size : 1_000_000new_primes = Array(Int64).new(new_primes_size) { |i| @@primes.last + (i + 1) * 2 }new_primes_max = new_primes.last@@primes.each do |prime|next if prime == 2break if prime * prime > new_primes_max# Here I use the technique of the Sieve of Sundaram. We can# only test against the odd multiple of the given prime.# min_composite is the minimum number that is greater than# the last confirmed prime, and is an odd multiple of# the given prime.min_multiple = ((@@primes.last // prime + 1) // 2 * 2 + 1) * primemin_multiple.step(by: prime * 2, to: new_primes_max) do |multiple|index = new_primes_size - (new_primes_max - multiple) // 2 - 1new_primes[index] = 0_i64endend@@primes.concat(new_primes.reject(0_i64))endprivate struct EachDivisor(T)include Enumerable(T)def initialize(@exponential_factors : Array(Array(T)))enddef eachArray.each_product(@exponential_factors) do |factors|yield factors.reduce { |a, b| a * b }endendend# Returns an enumerator that iterates through the all positive divisors of# the given number. **The order is not guaranteed.**# Not in the original Ruby's Prime library.## ```# AtCoder::Prime.each_divisor(20) do |n|# puts n# end # => Puts 1, 2, 4, 5, 10, and 20## AtCoder::Prime.each_divisor(10).map { |n| 1.0 / n }.to_a # => [1.0, 0.5, 0.2, 0.1]# ```def each_divisor(value : Int)raise ArgumentError.new unless value > 0factors = prime_division(value)if value == 1exponential_factors = [[value]]elseexponential_factors = factors.map do |(factor, count)|cnt = typeof(value).zero + 1Array(typeof(value)).new(count + 1) do |i|cnt_copy = cntif i < countcnt *= factorendcnt_copyendendendEachDivisor(typeof(value)).new(exponential_factors)end# :ditto:def each_divisor(value : T, &block : T ->)each_divisor(value).each(&block)endendendstruct Intdef prime?AtCoder::Prime.prime?(self)endendn = read_line.to_ia = read_line.split.map(&.to_i)x = a.map { |x|AtCoder::Prime.prime_division(x).sum(&.[1])}.reduce(0) { |acc, x|acc ^ x}puts x > 0 ? "white" : "black"