0
0

More than 3 years have passed since last update.

Atcoder ABC162 A-Dをpythonで

Last updated at Posted at 2020-04-13

A-Dまでの備忘録

A Lucky7

for文使ったけどif inでもよかった。

abc162a.py
a=list(input())
for i in a:
    if i=='7':
        print("Yes")
        exit()
print("No")

if inの場合

abc162a_2.py
a=input()
if '7' in a:
   print("Yes")
else:
   print("No")

B Fizzbuzz Sum

Fizzbuzzの出力は無視して、3でも5でも割り切れない数を足していくだけ

abc162b.py
n=int(input())
a=0
for i in range(n+1):
    if i%3!=0 and i%5!=0:  
        a+=i
print(a)

C Sum of gcd of Tuples (Easy)

今回からpython3のバージョンが上がったのでmath.gcdが使えるようになりました。
$gcd(a,b,c)=gcd(gcd(a,b),c)$はお約束

abc162c.py
import math
k=int(input())
ans=0
for i in range(1,k+1):
    for j in range(1,k+1):
        a=math.gcd(i,j)
        for x in range(1,k+1):
            ans+=math.gcd(a,x)

print(ans)

D RGB Triples

満たすパターンの総数はRの数×Gの数xBの数になる。例外としてi, j, kが等差数列になりかつそれぞれの色が異なる場合を除算する。等差数列の公差dのパターンは高々nなので素直に全探索する・・・としたらTLEした。
*後ほどpypy3で提出したら通った

abc162d_TLE.py
n=int(input())
s=input()

r=s.count('R')
g=s.count('G')
b=s.count('B')

ans=r*g*b

for i in range(n):
    for d in range(n):
        j=i+d
        k=j+d
        if k<n:
            if s[i]!=s[j] and s[j]!=s[k] and s[k]!=s[i]:
                ans-=1

print(ans)

k=nの時にbreakするとよい

abc162d.py
n=int(input())
s=input()

r=s.count('R')
g=s.count('G')
b=s.count('B')

ans=r*g*b

for i in range(n):
    for d in range(n):
        j=i+d
        k=j+d
        if k>=n: break
        if s[i]!=s[j] and s[j]!=s[k] and s[k]!=s[i]:
            ans-=1

print(ans)
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