LoginSignup
3
2

More than 3 years have passed since last update.

PythonでABC155のA~Cを解く

Posted at

はじめに

こんばんは、tax_freeです。前回からレートが28上がりました。茶色まで半分。今回はA~Cの三完でした。前回の記事に初めての質問が来て嬉しかったので、質問たくさんしてくれると嬉しいです。

A問題

問題

考えたこと
いいかんじに場合分けの数を減らそうとしたけど、思いつかなかったのでごり押しで場合分けしただけです。

a, b, c = map(int,input().split())

if a == b and a != c:
    print('Yes')
elif a == c and a != b:
    print('Yes')
elif b == c and a != b:
    print('Yes')
else:
    print('No')

B問題

問題
Bで少し考えてしまって時間をロスしたのが痛い

考えたこと
Aの要素全てが条件を満すかを調べています。cは3、5で割り切れた要素の数、dは偶数の個数です。

n = int(input())
a = list(map(int,input().split()))

d = 0
c = 0
for i in a:
    if i % 2 == 0:
        if i % 3 == 0 or i % 5 ==0:
            c += 1
        else:
            print('DENIED')
            quit()
        d += 1
if c == d:
    print('APPROVED')

C問題

問題
TLE:1

考えたこと
全ての要素の回数を調べるための方法を考えた結果、複数のlistを作って、要素ごとにカウントしていくしかないと結論ができました。自分の中で。
その結果、あまりに汚いコードが生れてしまいました。

n = int(input())
s = []
for i in range(n):
    s.append(input())

c = []
for j in s:
    if j not in c:
        c.append(j)

g = []
for t in c:
    g.append([s.count(t),t])
g.sort(reverse=True)
h = max(g)[0]
hh = []
for ii in range(len(g)):
    if g[ii][0] == h:
        hh.append(g[ii])
    else:
        break
hh.sort(key=lambda x: x[1])
ans = []
for k in range(len(hh)):
    print(hh[k][1])

重複なしで要素を数えるためのlist、要素の個数ごとにsortしたlist、要素の個数ごとにsortしたlistの最大値だけを集めたlist、そして、要素の個数ごとにsortしたlistの最大値だけを集めたlistをprintするためのlistが誕生しました。for t in cのように"in"を使うと計算量が激増するという知見を前々回くらいに得たはずなのに、"you can do it"と言いながら、submitしてました。TLE出ました。

ACだったコード
pythonの標準ライブラリのcollectionsを使います。

import collections

n = int(input())
s = []
for i in range(n):
    s.append(input())

c = collections.Counter(s)
c_s = c.most_common()
m = c.most_common()[0][1]
ans = []
for j in range(len(c_s)):
    if c_s[j][1] != m:
        break
    else:
        ans.append(c_s[j][0])
ans.sort()
for t in ans:
    print(t)

c.most_common()でどの要素が何個あるかを調べることができます。

まとめ

D、EはDPを感じたんですけど、どうなんでしょうか。期末テストも終わったのでDPとかアルゴリズムの勉強したいと思います。
おやすみなさい。また来週。

3
2
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
3
2