반응형

문제 출처 :


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



알고리즘 분석 :


문제 해결에 필요한 사항

1. 우선순위 큐 다익스트라 

개념 :: http://www.crocus.co.kr/546

접목 :: http://www.crocus.co.kr/545


다익스트라에 대한 개념을 이해하고 이 문제를 푼다면 쉽게 해결할 수 있는 문제이다.


코드 및 해답은 아래 소스 코드를 통해 확인할 수 있다.


소스 코드 : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h>
#include <cstdio>
 
#define MAX_V 20001
 
using namespace std;
 
// 그래프의 인접 리스트. (연결된 정점 번호, 간선 가중치) 쌍을 담아야 한다.
vector< pair<intint>> adj[MAX_V]; // 정점의 최대 개수 :: MAX_V
 
vector<int> dijkstra(int src, int V, int E)
{
    // V만큼 배열을 INT_MAX로 초기화
    vector<int> dist(V, INT_MAX);
    dist[src] = 0// 시작점은 0으로 초기화 한다. 
 
    priority_queue<pair<intint> > pq;
 
    pq.push(make_pair(0, src)); // 시작점을 처음으로 우선순위 큐에 삽입
 
    while (!pq.empty())
    {
        // 우선순위 큐에 음의 가중치로 들어가 있으니 양으로 바꾸어준다.
        int cost = -pq.top().first;
        int here = pq.top().second;
 
        pq.pop();
 
        // 만약 지금 꺼낸 것보다 더 짧은 경로를 알고 있다면 지금 꺼낸것을 무시한다.
        if (dist[here] < cost)
            continue;
 
        // 인접한 정점들을 모두 검사.
        for (int i = 0; i < adj[here].size(); i++)
        {
            int there = adj[here][i].first;
            int nextDist = cost + adj[here][i].second;
 
            // 더 짧은 경로를 발견하면, dist[]를 갱신하고 우선순위 큐에 넣는다.
            // dist 벡터에는 시작점 -> there 위치까지의 최단 거리가 담겨있다.
            if (dist[there] > nextDist)
            {
                dist[there] = nextDist;
                pq.push(make_pair(-nextDist, there));
                /*
                여기서 -로 넣는 이유?
                priority_queue STL은 기본적으로 가장 큰 원소가 위로 가도록 큐를 구성
                따라서 거리의 부호를 바꿔서 거리가 작은 정점부터 꺼내지도록 하기 위함
                */
            }
        }
    }
 
    return dist;
}
 
 
int main()
{
    int n, m;
    int from, to, val;
    scanf("%d %d"&n, &m);
 
    n++;
 
    for (int i = 0; i < m; i++)
    {
        scanf("%d %d %d"&from, &to, &val);
        adj[from].push_back(make_pair(to, val));
    }
 
    int start, end;
    scanf("%d %d"&start, &end);
    vector<int> ans = dijkstra(start, n, m);
 
    cout << ans[end];
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형

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

[1715번] 카드 정렬하기  (0) 2017.02.28
[2583번] 영역 구하기  (0) 2017.02.27
[9248번] Suffix Array  (0) 2017.02.25
[1605번] 반복 부분문자열  (0) 2017.02.25
[4883번] 삼각 그래프  (0) 2017.02.24