LoginSignup
0
0

More than 1 year has passed since last update.

Atcoder ABC212 Python C問題振り返り

Last updated at Posted at 2021-08-01

前書き

C問題でACできなかったので今回も振り返っていきます。
Atcoder Factsという問題ごとの正解率をレート帯ごとに出してくれるサイトを見たところ、200-399のレートにいる人達の正解率が63.85%だったので解けるようにしておきたいですね...

自分の提出(TLE)

ソートするところまでは良かったのですが、その後でどうすればよいか全く浮かびませんでした。

N, M = map(int,input().split())
A_2 = list(map(int,input().split()))
B_2 = list(map(int,input().split()))

A = sorted(A_2)
B = sorted(B_2)

ans = 0

if A[-1] <= B[0]:
  ans = B[0] - A[-1]
  print(ans)
  exit()
elif B[-1] <= A[0]:
  ans = A[0] - B[-1]
  print(ans)
  exit()

flg = []
Ans = []

for i in range(N):
  a = abs(A[i] - B[0])
  b = abs(A[i] - B[-1])
  if a > b:
    for j in range(-1,-M//2,-1):
      flg.append(abs(A[i] - B[j]))
    Ans.append(min(flg))
    flg = []
  elif a <= b:
    for j in range(0,M//2):
      flg.append(abs(A[i] - B[j]))
    Ans.append(min(flg))
    flg = []

ans = min(Ans)
print(ans)

修正後の提出(AC確認済み)

Atcoderで解説動画を出してくださっているsnukeさんの解説を聞くことで実装できました。
snukeさんの解説は図を書いて視覚的に説明して下さるのでとても分かりやすいです。
(いつもありがとうございます...)

import math
N, M = map(int,input().split())
A_2 = list(map(int,input().split()))
B_2 = list(map(int,input().split()))

A = sorted(A_2)
B = sorted(B_2)

a = 0
b = 0
ans = math.inf

while a < N and b < M:
  ans = min(ans, abs(A[a] - B[b]))
  if A[a] < B[b]:
    a += 1
  else:
    b += 1
print(ans)

感想

AとBのリストをソートしてあげて、それぞれにカーソルを用意して(このコードでいうaとb)、一つずつ進めてあげるイメージらしいです。(片方のカーソルの位置を超えたタイミングで超えられた方のカーソルを進めていく)
リストBの要素をソート後のリストAに入れて(ソートされている状態をくずさないで)、両隣との差を出していくのかなと考えていましたが、カーソルをイメージするやり方の方が個人的に分かりやすいなと感じました。

0
0
0

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