알고리즘/SWEA

[Python] SWEA 6485: 삼성시의 버스 노선

suwonieee 2023. 2. 9. 17:24

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWczm7QaACgDFAWn&categoryId=AWczm7QaACgDFAWn&categoryType=CODE&problemTitle=485&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

처음에 문제를 접했을 때는 5000까지의 리스트를 버스 개수만큼 만들고(tmp) 만일 버스가 정류장을 경유한다면 값을 1로 바꿔준 후, 각 리스트들을 더해 결과를 도출하려고 했다. 

 

1차 시도

더보기
T = int(input())
for tc in range(1, T+1):
    N = int(input())
    new = []
    for n in range(1,N+1):
        A,B = map(int, input().split())

        tmp = [0]*5001
        for i in range(A-1,B):
            tmp[i] = 1
        new.append(tmp)
    #new는 list의 list 형태

    ans = [x+y for x,y in zip(new[0], new[1])] #필수.  #정류장을 들리는 버스의 수를 뽑아냄. A와 B 노선만 다니기 대문에 new에는 두 개의 원소만 존재하고 zip을 사용할 수 있다.

    P= int(input())
    res = []
    for p in range(P):
        C = int(input())
        res.append((ans[C-1]))

    print(f'#{tc}', *res, sep=' ')

시간이 꽤나 걸리긴 했지만 어쨌거나 주어진 TC랑도 잘 맞아 떨어져서 풀었군... 싶었지만 fail이 떴고 다시 한 번 짚어보니 TC의 경우 노선이 두 개지만 n개의 노선이 생길 수 있다는 것을 고려하지 못했다. 중간에 주석을 보면 그냥 문제를 잘못 접근한 거 같다는 생각도 적지않게 든다................... TC만 보고 납작하게 문제를 안 봐야 할텐데

 

2차 시도

더보기
T = int(input())
for tc in range(1, T+1):
    N = int(input())
    new = []
    for n in range(1,N+1):
        A,B = map(int, input().split())

        tmp = [0]*5001
        for i in range(A-1,B):
            tmp[i] = 1
        print(tmp)
        new.append(tmp)
    #new는 list의 list 형태

    for i in range(1, len(new)):
        new = [x+y for x,y in zip(new[0], new[i])]
    ans = new

    P= int(input())
    res = []
    for p in range(P):
        C = int(input())
        res.append((ans[C-1]))

    print(f'#{tc}', *res, sep=' ')

그래서 ans를 구하는 부분을 for문을 넣어서 더해주는 방법으로 수정했고 이제는 정말 다 풀었군 싶었지만...! 지독한 런타임 에러에 걸렸다

 

ANS

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    new = []
    cnt = [0]*5001
    for n in range(N):
        S,E = map(int, input().split())

        for i in range(S, E+1):
            cnt[i] += 1

    P = int(input())
    lst = []
    for k in range(P):
        p = int(input())
        lst.append(cnt[p])

    print(f'#{tc}', *lst)

풀이 방식을 바꿔서 cnt 이용해서 접근하니 수월한 문제.