백준 No.11779 [최소비용 구하기2]
본문 바로가기
Algorithm (C++ based)/BOJ

백준 No.11779 [최소비용 구하기2]

by 조훈이 2021. 2. 19.

BOJ No.11779 [최소비용 구하기2]


 Problem 

 

11779번: 최소비용 구하기 2

첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스

www.acmicpc.net


 Code 

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
#include <iostream>
#include <queue>
#include <vector>
#define cost first
#define ver second
 
using namespace std;
typedef pair<intint> PII;
typedef unsigned long long ull;
 
int V, E;
int from, to;
const ull INF = 9000000000000000000;
vector<vector<PII>> node;
 
void solved(int from, int to) {
    vector<ull> cost_to(V + 1, INF);
    vector<queue<int>> sequence(V + 1);
    priority_queue<PII, vector<PII>, greater<PII>> pq;
 
    cost_to[from] = 0;
    pq.push(PII(cost_to[from], from));
    sequence[from].push(from);
 
    while (!pq.empty()) {
        PII cur = pq.top();
        pq.pop();
 
        if (cur.cost > cost_to[cur.ver]) continue;
        
        for (int i = 0; i < node[cur.ver].size(); i++) {
            PII next = node[cur.ver][i];
            next.cost += cur.cost;
 
            if (cost_to[next.ver] > next.cost) {
                sequence[next.ver] = sequence[cur.ver];
                sequence[next.ver].push(next.ver);
 
                cost_to[next.ver] = next.cost;
                pq.push(next);
            }
        }
    }
 
    cout << cost_to[to] << '\n';
    cout << sequence[to].size() << '\n';
 
    int seqSize = sequence[to].size();
 
    while (seqSize--) {
        cout << sequence[to].front() << ' ';
        sequence[to].pop();
    }
}
 
int main() {
    cin >> V >> E;
    node.resize(V + 1);
 
    for (int i = 0; i < E; i++) {
        int s, e, cst;
        cin >> s >> e >> cst;
 
        node[s].push_back(PII(cst, e));
    }
 
    cin >> from >> to;
 
    solved(from, to);
}
cs

 How to solve 

출력 조건

  출력 조건의 둘째, 셋째 조건이 없다면 그냥 정말 기본적인 다익스트라 문제이며, 1916번: 최소비용 구하기 가 이에 해당한다.

 

  기존 다익스트라의 형태에 #18 line 과 같이 sequence[ i ]를 선언해 주었다.

vector<queue<int>> sequence(V + 1);

  • sequence[ i ] : vertex from 부터 vertex i 까지 가는 최소 비용 경로를 담는 queue 이다.

    #23, #36 ~ #37 에서 sequence에 대해 최신화를 해준다.

 

  • #23 : vertex from 에서 vertex from 까지 sequnce인 sequence[from] 에 vertex from 을 push 해준다.
  • #36 ~ #37 : 현재까지의 cost_to[next.ver] 보다 cur.ver을 경유하고 next.ver에 가는 cost인 next.cost가 더 작을 경우 sequence[next.ver]를 업데이트 해준다. 업데이트는, sequence[next.ver]sequence[cur.ver]next.ver를 하나 더 push되도록 업데이트 해주면 된다.

  그리고 둘째 셋째 조건은, sequence[to]의 크기, 그리고 sequence[to]front(), pop()을 해 가면서 프린트 하면 된다.

728x90

'Algorithm (C++ based) > BOJ' 카테고리의 다른 글

백준 No.7579 [앱]  (0) 2021.02.22
백준 No.11404 [플로이드]  (0) 2021.02.20
백준 No.13913 [숨바꼭질4]  (0) 2021.02.16
백준 No.13549 [숨바꼭질3]  (0) 2021.02.16
백준 No.1504 [특정한 최단 경로]  (0) 2021.02.09

댓글