happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (300)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (53)
      • DevOps (3)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Patch
  • kubernetes
  • apply
  • 15
  • 18
  • replace
  • edit

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[python] 백준 > 다익스트라 > 최단 거리(1753)
알고리즘/알고리즘 문제

[python] 백준 > 다익스트라 > 최단 거리(1753)

2021. 2. 2. 23:49

[문제]

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.

 

www.acmicpc.net/problem/1753

 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다.

www.acmicpc.net

[나의 풀이 - 실패버전]

import sys
import heapq
input = sys.stdin.readline

V, E = map(int, input().split())
start_node = int(input())
graph = [[] for _ in range(V+1)]
arr = [list(map(int, input().split())) for _ in range(E)]
for start, end, cost in arr:
    graph[start].append((cost, end))


def dijkstra(s_node, e_node):
    heap = []
    distance = [sys.maxsize for _ in range(V + 1)]
    heapq.heappush(heap, (0, s_node))
    distance[s_node] = 0
    while heap:
        h_cost, h_node = heapq.heappop(heap)
        for c, e in graph[h_node]:
            sum_cost = h_cost+c
            if sum_cost < distance[e]:
                distance[e] = sum_cost
                heapq.heappush(heap, (c, e))
    return distance[e_node]


answer = []
for end_node in range(1, V+1):
    answer = dijkstra(start_node, end_node)
    if answer == sys.maxsize:
        answer = 'INF'
    print(answer)

  • while문으로 heap을 돌리면서 heappush를 해줄 때 sum_cost를 넣어줘야 하는데 그냥 c를 넣어줬다.
  • 다익스트라 함수를 한번 돌리고 나온 distance에서 값을 출력해주면 되는데 바보같이 매번 다른 end_node에 대한 다익스트라 함수를 매번 호출시켜줬다.

 

[나의 풀이 - 성공버전]

import sys
import heapq
input = sys.stdin.readline

V, E = map(int, input().split())
K = int(input())
distance = [sys.maxsize]*(V+1)
arr = [list(map(int, input().split())) for _ in range(E)]
graph = [[] for _ in range(V+1)]
for start, end, cost in arr:
    graph[start].append((cost, end))
heap = []


def dijkstra(s_node):
    heapq.heappush(heap, (0, s_node))
    distance[s_node] = 0
    while heap:
        h_cost, h_node = heapq.heappop(heap)
        if h_cost > distance[h_node]:
            continue
        for c, e in graph[h_node]:
            sum_cost = h_cost+c
            if sum_cost < distance[e]:
                distance[e] = sum_cost
                heapq.heappush(heap, (sum_cost, e))


dijkstra(K)
for i in range(1, V+1):
    print('INF' if distance[i] == sys.maxsize else distance[i])

 

 

[다른 사람의 풀이(C++)]

#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
int v, e, s, x, y, z, d[20002];
vector<vector<pair<int, int>>> vt;
int main() {
	scanf("%d%d%d", &v, &e, &s);
	vt.resize(v + 1);
	for (int i = 0; i < e; i++) {
		scanf("%d%d%d", &x, &y, &z);
		vt[x].push_back({ y,z });
	}
	memset(d, -1, sizeof(d));
	priority_queue<pair<int, int>> pq;
	pq.push({ 0,s });
	while (pq.size()) {
		int here = pq.top().second;
		int cost = -pq.top().first;
		pq.pop();
		if (d[here] != -1)
			continue;
		d[here] = cost;
		for (auto it : vt[here]) {
			int next = it.first;
			int acost = -it.second - cost;
			if (d[next] != -1)
				continue;
			pq.push({ acost,next });
		}
	}
	for (int i = 1; i <= v; i++) {
		if (d[i] == -1)puts("INF");
		else printf("%d\n", d[i]);
	}
	return 0;
}

'알고리즘 > 알고리즘 문제' 카테고리의 다른 글

[python] 백준 > 이분 탐색 > 수 찾기(1920)  (0) 2021.02.03
[python] 백준 > 이분 탐색 > 랜선 자르기(1654)  (0) 2021.02.03
[python] 백준 > bfs > 아기상어(16236)  (0) 2021.02.02
[python] 백준15686 > 부루트포스 > 치킨 배달  (0) 2021.02.01
[python] 백준 > 부루트포스 > 백설 공주와 일곱 난쟁이  (0) 2021.01.29
    '알고리즘/알고리즘 문제' 카테고리의 다른 글
    • [python] 백준 > 이분 탐색 > 수 찾기(1920)
    • [python] 백준 > 이분 탐색 > 랜선 자르기(1654)
    • [python] 백준 > bfs > 아기상어(16236)
    • [python] 백준15686 > 부루트포스 > 치킨 배달
    happyso
    happyso

    티스토리툴바