문제 풀이

 

방향 그래프이면서 하나의 시작점에서 다른 여러 개의 모든 지점의 최단 경로를 구하는 방법은 다익스트라 알고리즘을 구현하면 해결할 수 있다.

 

소스 코드 (우선순위 큐를 이용한 구현)

 

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;

const int INF = 987654321;

int V, E, startNode;
vector<pair<int, int> > edges[20001];
int dist[20001];

void dijkstra()
{
    dist[startNode] = 0;
    priority_queue<pair<int, int> > pq;
    pq.push({0, startNode});
    while(!pq.empty())
    {
        int distance = -pq.top().first;
        int curNode = pq.top().second;
        pq.pop();
        
        if(dist[curNode] < distance)
            continue;
        
        for(int i = 0; i < edges[curNode].size(); i++)
        {
            int nextNode = edges[curNode][i].first;
            int nextDistance = edges[curNode][i].second + distance;
            if(nextDistance < dist[nextNode])
            {
                dist[nextNode] = nextDistance;
                pq.push({-nextDistance, nextNode});
            }
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> V >> E >> startNode;
    fill(dist, dist + 20001, INF);
    for(int i = 0; i < E; i++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        
        edges[u].emplace_back(v,w);
    }
    
    dijkstra();
    
    for(int i = 1; i <= V; i++)
    {
        if(dist[i] == INF)
            cout << "INF\n";
        else
            cout << dist[i] << '\n';
    }
    
    return 0;
}

'Algorithm' 카테고리의 다른 글

[백준 17298] 오큰수  (0) 2021.10.11
[백준 14425] 문자열 집합  (0) 2021.10.11
[HackerRank] 2D Array - DS  (0) 2021.09.09
[프로그래머스] 방문 길이 (C++)  (0) 2021.06.04
[프로그래머스] 영어 끝말잇기 (C++)  (0) 2021.06.04

+ Recent posts