0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyでAtCoder ABC277(A, B, C)を解いてみた

Last updated at Posted at 2023-04-21

はじめに

Webエンジニアを目指して、RubyやRailsをいじってます。
今回は、RubyでAtCoder ABC277のA, B, Cを解きました。備忘録として解き方をまとめていきたいと思います。

A - ^{-1}

a-277.rb
n, x = gets.split.map(&:to_i)
m = gets.split.map(&:to_i)
puts m.index(x) + 1

解説

indexメソッドを使って、xと一致する要素の位置を特定しています。

B - Playing Cards Validation

b-277.rb
n = gets.to_i
array1 = ["H", "D", "C", "S"]
array2 = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]
s_array = Array.new(n){ gets.chomp }

hash = {}
s_array.each do |s|
  if hash[s]
    puts "No"
    exit
  end
  hash[s] = true

  unless array1.include?(s[0]) && array2.include?(s[1])
    puts "No"
    exit
  end
end
puts "Yes"

<追記>
コメントでいただいた別解になります。

別解
C1 = "HDCS".chars
C2 = "A23456789TJQK".chars

n = gets.to_i
ss = Array.new(n) { gets.chomp }

f = ss.all? { _1.start_with?(*C1) }
f = f && ss.all? { _1.end_with?(*C2) }
f = f && (ss.uniq.size == n)
puts f ? "Yes" : "No"

解説

問題文の通りに実装していき、条件を満たさない文字列があればNoを出力して終了、すべての文字列が条件を満たしていればYesを出力します。

C - Ladder Takahashi

c-277.rb
n = gets.to_i

hash = Hash.new { |h, k| h[k] = [] }
n.times do
  a, b = gets.split.map(&:to_i)
  hash[a] << b
  hash[b] << a
end

searched = Hash.new(false)
searched[1] = true
stack = [1]

while node = stack.pop
  hash[node].each do |factor|
    next if searched[factor]
    searched[factor] = true
    stack << factor
  end
end
puts searched.keys.max

<追記>
コメントでいただいた別解になります。再帰を使って解くこともできます。

別解
n = gets.to_i
abs = Array.new(n) { gets.split.map(&:to_i) }

ladders = Hash.new { |h, k| h[k] = [] }
abs.each do |a, b|
  ladders[a] << b
  ladders[b] << a
end

max = 1
visited = {}
go = ->(floor) {
  return if visited[floor]
  visited[floor] = true
  max = floor if floor > max
  ladders[floor].each { go.(_1) }
}
go.(1)
puts max

解説

DFSを使って実装しました。出力するのは、1から出発してたどりつける最大の階数なので、searched.keys.maxを使って対応させています。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?