본문 바로가기
백준

백준 1916 최소비용 구하기

by 콩순이냉장고 2021. 7. 23.

문제 URL : https://www.acmicpc.net/problem/1916

 

1916번: 최소비용 구하기

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

www.acmicpc.net

 

문제 접근법 : 

 

다익스트라 알고리즘을 묻는 문제입니다.

pq를 이용하여 다익스트라를 이용하고 거기에더해 필요없는 탐색을 가지치기 할줄알아야 시간초과에서 벗어날수있습니다.

 

소스코드 : 

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
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int n, m,start,finish;
vector<vector<pair<intint>>>v;
void input() {
    cin >> n;
    cin >> m;
    v = vector<vector<pair<intint>>>(n+1);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        v[a].push_back({ b,c });
    }
    cin >> start >> finish;
}
 
int dijkstrak() {
    priority_queue<pair<intint>> pq;
    vector<int> dist(n + 11e9);
    pq.push({ 0,start });
    dist[start] = 0;
    while (!pq.empty()) {
        int cur = pq.top().second;
        int cost = -pq.top().first;
        pq.pop();
        if (dist[cur] < cost)
            continue;
        for (int i = 0; i < v[cur].size(); i++) {
            int next = v[cur][i].first;
            int ncost = cost + v[cur][i].second;
            if (dist[next] > ncost) {
                dist[next] = ncost;
                pq.push({ -ncost,next });
            }
        }
    }
    return dist[finish];
}
void solve() {
 
    cout << dijkstrak() << "\n";
}
 
 
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt", "r", stdin);
    input();
    solve();
    
 
}
 
 
cs

 

궁금한점 혹은 모르는점 어떤질문이든 댓글은 언제나 환영입니다.

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

백준 3447 버그왕  (0) 2021.07.23
백준 9996 한국이 그리울 땐 서버에 접속하지  (0) 2021.07.23
백준 14426 접두사 찾기  (0) 2021.07.16
백준 12904 A와 B  (0) 2021.07.15
백준 16934 게임 닉네임  (0) 2021.07.11