https://www.acmicpc.net/problem/1238

 

1238번: 파티

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어

www.acmicpc.net


내 풀이

시도1

def solution():
    INF = int(1e9)
    n,m,x=map(int,input().split())
    time_list=[]
    result=[[]]
    
    graph = [[] for _ in range(m+1)]
    
    for _ in range(m):
        a,b,c= map(int,input().split())
        graph[a].append((b,c))
      
    def get_smallest_node():
        min_value = INF
        index = 0
        for i in range(1, n+1):
            if distance[i] < min_value and not visited[i]:
                min_value = distance[i]
                index = i
        return index
    def ekdlrtmxmfk(start):
        distance[start]=0
        visited[start]=1
        
        for j in graph[start]:
            distance[j[0]]=j[1]
        for _ in range(n-1):
            now = get_smallest_node()
            visited[now] = True
        
            for j in graph[now]:      
                cost = distance[now] + j[1]

                if cost<distance[j[0]]:
                    distance[j[0]] = cost
        return distance
    for i in range(1,n+1):
        distance = [INF] * (n+1)
        visited = [0] * (n+1)
        result.append(ekdlrtmxmfk(i))

    for i in range(1, n+1):
        time_list.append(result[i][x] + result[x][i])
    
    print(max(time_list))

시간초과가 났다. 특정 한 점에서 다른 모든점까지의 거리를 구하는 부분에서 다익스트라는것을 알았지만 단 한번도 다익스트라 문제를 풀면서 heapq를 사용하지 않은적이 없어서 문득 그냥 구현하면 통과가 될까싶어 한번해보았다.

 

시도2

import sys
import heapq

input = sys.stdin.readline
INF = int(1e9)


def solution():
    n,m,x = map(int,input().split())
    graph =[[] for _ in range(n+1)]

    for _ in range(m):
        a,b,c = map(int,input().split())
        graph[a].append((b,c))
    
    def ekdlrtmxmfk(start):
        q = []
        heapq.heappush(q,(0,start))
        distance[start] = 0

        while q:
            dist,now = heapq.heappop(q)
            
            for i in graph[now]:
                cost = dist + i[1]
                if cost < distance[i[0]]:
                    distance[i[0]]=cost
                    heapq.heappush(q,(cost,i[0]))
        return distance
    
    result = [[]]
    dis =[]

    for i in range(1,n+1):
        distance= [INF] * (n+1)
        result.append(ekdlrtmxmfk(i))
    for i in range(1,n+1):
        dis.append(result[i][x]+result[x][i])
    print(max(dis))
    

solution()

원리는 같은데 heapq를 사용한 방법이다. 



다른사람의 풀이

 



최근에 기사시험을 시작으로 본격적인 취준이 시작되었다. 아직 한학기가 남긴했지만 지원가능한 회사에 꽤나 많이 지원했는데(다행히도 서류는 꽤 많이 붙었다) 저번주부터 코딩테스트가 시작되었다. 18학점을 들어야하는 상황이라 학교 중간고사도 겹치다보니 쉽지않다..

하루에 하나정도는 문제를 꼭 풀어야겠다 + sql도

'취준 > 백준' 카테고리의 다른 글

10816(숫자카드 2) - 파이썬  (0) 2022.10.27
1806(부분합) - 파이썬  (0) 2022.10.24
25755 - 파이썬  (0) 2022.10.21
1912(연속합) - 파이썬  (0) 2022.10.18
2589(보물섬) - 파이썬  (0) 2022.09.02

https://www.acmicpc.net/problem/1504

 

1504번: 특정한 최단 경로

첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존

www.acmicpc.net


내 풀이

 

import sys
import heapq

INF = int(1e9)
input = sys.stdin.readline
def solution():
    N,E = map(int,input().split())
    graph = [[] for _ in range(N+1)]

    for _ in range(E):
        a,b,c = map(int,input().split())
        graph[a].append((b,c))
        graph[b].append((a,c))
    
    def ekdlrtmxmfk(start):
        distance = [INF] * (N+1)
        distance[start]=0
        q=[]
        heapq.heappush(q,(0,start))
        while q:
            dist,now = heapq.heappop(q)
            if distance[now] < dist:
                continue
            for i in graph[now]:
                cost = i[1] + dist
                if cost < distance[i[0]]:
                    distance[i[0]] = cost
                    heapq.heappush(q,(cost,i[0]))
        return distance
    
    
    x,y = map(int,input().split())

    original = ekdlrtmxmfk(1)
    #print(original)
    p1=ekdlrtmxmfk(x)
    #print(p1)
    p2=ekdlrtmxmfk(y)
    #print(p2)
    p1_path = original[x] + p1[y] + p2[N]
    p2_path = original[y] + p2[x] + p1[N]

    #print(p1_path,p2_path)
    answer = min(p1_path,p2_path)

    print(answer if answer <INF else -1)


solution()

최초에 문제 이해가 안됐다. 특정 노드를 반드시 거쳐가야한다는게 무슨말이지?

어차피 특정 노드를 거쳐가야하지않나?

잘 생각해보니

주어진 노드가 a,b,c,d 이고 특정 노드가 b,c라고하면

 

a -> d -> b- >c

혹은 

a -> c ->d ->b

이런식으로도 갈 수 있는데 이런 경우는 배제하고

무조건

a -> b -> c -> d 혹은

a -> c->b ->d 의 순서로 가라는 뜻이였다.

 

그러니까 최초 시작점 to 특정노드1 + 특정노드 1 to 특정노드 2 + 특정노드2 to 끝까지 or

               최초 시작점 to 특정노드2 + 특정노드 2 to 특정노드 1  + 특정노드1 to 끝까지 

중 최소 값을 택하면되는거다.  

                


다른사람의 풀이

import sys; input = sys.stdin.readline
from heapq import heappush, heappop

def dijkstra(start, end):
    dis = [0xffffff] * (N + 1)
    dis[start] = 0
    q = [[0, start]]
    while q:
        k, u = heappop(q)
        if k > dis[u]: continue
        for w, v in G[u]:
            if dis[v] > dis[u] + w:
                dis[v] = dis[u] + w
                heappush(q, [dis[v], v])

    return dis[end]

N, E = map(int, input().split())
G = [[] for _ in range(N + 1)]
for _ in range(E):
    u, v, w = map(int, input().split())
    G[u].append([w, v])
    G[v].append([w, u])

stop1, stop2 = map(int, input().split())

# 1 -> stop1 -> stop2 -> N
path1 = dijkstra(1, stop1) + dijkstra(stop1, stop2) + dijkstra(stop2, N)
# 1 -> stop2 -> stop1 -> N
path2 = dijkstra(1, stop2) + dijkstra(stop2, stop1) + dijkstra(stop1, N)

if path1 >= 0xffffff and path2 >= 0xffffff:
    print(-1)
else:
    print(min(path1, path2))

 


 

'취준 > 백준' 카테고리의 다른 글

1707 - 파이썬  (0) 2022.08.02
16928 - 파이썬  (0) 2022.08.01
7569 - 파이썬  (0) 2022.07.26
7576 - 파이썬  (0) 2022.07.14
2606 - 파이썬  (0) 2022.07.13

https://school.programmers.co.kr/learn/courses/30/lessons/12978

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


내 풀이

 

1.

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

def solution(N,road,K):
    graph = [[] for _ in range(N+1)]
    distance = [INF] * (N+1)
    distance[1]=0
    for r in road:
        graph[r[0]].append((r[1],r[2]))
        graph[r[1]].append((r[0],r[2]))
    def ekdlrtmxmfk():
        q=[]
        heapq.heappush(q,(0,1))
        
        while q:
            dist,now = heapq.heappop(q)
            #print((dist,now))
            #print(dist)
            if distance[now] < dist:
                continue
            for i in graph[now]:
                cost = dist + i[1]
                if cost < distance[i[0]]:
                    distance[i[0]] = cost
                    heapq.heappush(q,(cost,i[0]))
    ekdlrtmxmfk()
    #print(graph)
    #print(distance)
    return len([x for x in distance if x<=K])

2.

 

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

def solution(N,road,K):
    graph = [[] for _ in range(N+1)]
    distance = [INF] * (N+1)
    distance[1]=0
    for r in road:
        graph[r[0]].append((r[2],r[1]))
        graph[r[1]].append((r[2],r[0]))
    def ekdlrtmxmfk():
        q=[]
        heapq.heappush(q,(0,1))
        
        while q:
            dist,now = heapq.heappop(q)
            #print((dist,now))
            #print(dist)
            if distance[now] < dist:
                continue
            for i,j in graph[now]:
                if i+dist < distance[j]:
                    distance[j] = i+dist
                    heapq.heappush(q,(dist+i,j))
    ekdlrtmxmfk()
    
    return len([x for x in distance if x<=K])

대표적인 다익스트라 알고리즘이다.

너무 오랜만에 풀어서 진짜 한참 헤맸다..

처음에는 visit를 만들어서 풀었는데, 시간초과 나서 heapq을 썼다.

다익스트라 알고리즘이 적용가능할 때는 음의 값이 없을때임을 명심해야한다.

1 번풀이 2번풀이 둘다 비슷한데 1번은 이코테의 내용을 참고했다.

1번이 좀 더 직관적인 풀이법같다.

두 풀이법의 가장 큰 차이점은, (노드,가중치 ) 의 순서가 다르다.

 


다른사람의 풀이

 

 



 

'취준 > 프로그래머스' 카테고리의 다른 글

두 큐 합 같게 만들기 - 파이썬  (0) 2022.08.31
성격 유형 검사하기 - 파이썬  (0) 2022.08.31
괄호 회전하기 - 파이썬  (0) 2022.07.25
게임 맵 최단거리 - 파이썬  (0) 2022.07.05
조이스틱 - 파이썬  (0) 2022.07.03

+ Recent posts