본문 바로가기
Problem Solving/SWEA

[ SWEA ] D2 - 1940, 1928, 1288, 1284, 1204 - python 문제풀이

by IM조이 2021. 6. 28.

1940 가랏 RC카
접근법 : 커맨드가 0이 아닐 경우에만 뭔가 계산을 해주고, 0일때는 바로 현재 속도만 더해주면 된다

for tc in range(int(input())):
    commands = int(input())
    distance = 0
    current_speed = 0
    for _ in range(commands):
        info = input()
        if info != "0": #앞에서 1인지2인지도 비교안하고 빠질수있음
            command = info.split(" ")[0]
            acceleration = int(info.split(" ")[1])
            if command == "2" and current_speed < acceleration:
                current_speed = 0
            elif command == "2":
                current_speed -= acceleration
            else: #command == 1 : 가속
                current_speed += acceleration
        distance += current_speed
    print("#{} {}".format(tc+1,distance))

예전에 처음 이 문제를 풀었을 때는 0은 생각 안하고, 1인지 2인지 판별하는 코드만 작성했었는데 (아래)

for tc in range(int(input())):
    commands = int(input())
    current_speed = 0
    distance = 0
    for i in range(commands):
        info = input()
        if info[0] == '1':
            current_speed += (int(info[2]))
        elif info[0] == '2':
            if int(info[2]) < current_speed:
                current_speed -= (int(info[2]))
            else:
                current_speed = 0
        distance += abs(current_speed)
    print("#{} {}".format(tc+1, distance))

(위) 0인지 먼저 체크해줬을 때 (아래) 1인지 2인지만 체크했을때

속도는 0으로 먼저 분기해줬을때가 더 빠른듯하다

 

1928 Base64 디코더
한 번에 문제를 이해하기가 조금 까다롭기는 한데 간단히 원리만 정리해보면 이렇다

(이 문제에서 정한 인코딩 방식)

=> 문제의 요구사항 : 그럼 너네가 이제 디코딩 해봐 

d = {"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,
     "K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,
     "U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,
     "e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,
     "o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,
     "y":50,"z":51,"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,
     "8":60,"9":61,"+":62,"/":63}
for tc in range(int(input())):
    S = input()
    temp = ''
    result = ''
    for character in S:
        tobinary = bin(d[character])[2:]
        if len(tobinary) < 6:
            tobinary = "0"*(6-len(tobinary)) + tobinary
        temp += tobinary
    for i in range(0,len(temp),8):
        result+= chr(int('0b'+temp[i:i+8],2))
    print("#{} {}".format(tc+1, result))

 

1288 새로운 불면증 치료법
접근법 : 중복이 허용되지 않는 세트의 특징을 활용해서 매번 세트의 길이를 세어주는 방식
참고로 이 문제는 결과로 무엇을 출력해야하는지 주의깊게 봐야하는 문제다(습관적으로 카운트 내지 말고 ㅎㅎ)

for tc in range(int(input())):
    N = int(input())
    collections = set()
    cnt = 1
    while True:
        for number in list(str(N)):
            collections.add(number)
        if len(collections) == 10:
            break
        N //= cnt
        cnt += 1
        N *= cnt
    print("#{} {}".format(tc+1, N))

 

1284 수도요금 경쟁

for tc in range(int(input())):
    P,Q,R,S,W=map(int,input().split())
    print("#{} {}".format(tc+1, min(P*W,Q) if W<=R else min(P*W,Q+S*(W-R))))

 

1204 최빈수 구하기
처음에 풀 때는 최대값 크기 만큼의 배열을 만들어서 카운트를 올려가면서 풀었는데, 만약 [1,1,1,1,1,.....,100000000000] 이런 배열이라도 들어오면 쓸데없는 메모리낭비가 심해진다. 그래서 두번째 풀 때는 딕셔너리로 풀었다.
- 딕셔너리로 풀 때 주의해야할 점은 파이썬 버전에 따라서 딕셔너리 키가 정렬이 안 되기때문에 갱신해줄때 밸류값, 키값 모두 비교를 해줘야 테스트케이스 3번에서 답이 79인데 77로 출력되는 에러가 나오지 않는다.

from collections import defaultdict
for tc in range(int(input())):
    N = int(input())
    numbers = list(map(int, input().split()))
    d = defaultdict(int)
    max_value = 0
    result = 0
    for number in numbers:
        d[number] +=1
    for k,v in d.items(): 
        if v > max_value:
            result,max_value = k,v
        elif v == max_value and result<k:
            result = k
    print("#{} {}".format(tc+1, result))

 

댓글