기억보다는 기록을 해볼까

[BOJ] 최소비용 구하기 1916 (C++) - 40일차 본문

백준으로 C++ 공부하기

[BOJ] 최소비용 구하기 1916 (C++) - 40일차

옥상에서 2021. 12. 21. 20:01
728x90

문제

 

1916번: 최소비용 구하기

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

www.acmicpc.net

생각

어제 공부한 다익스트라 알고리즘을 그대로 사용했다.

참고

 

 

[BOJ] 최단경로 1753 (C++) - 39일차

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

jees.tistory.com

코드

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

const int INF = 987654321;

vector<pair<int, int>> graph[1001];
int d[1001] = {0, };
priority_queue<pair<int,int>> pq;

void dijkstra (int start) { 
    
    pq.push({0, start});
    d[start] = 0;

    while(!pq.empty()) {
        int dist = - pq.top().first; //현재 노드까지의 비용
        int now = pq.top().second; // 현재 노드
        pq.pop();
        
        if(d[now] < dist) // 이미 최단경로를 체크한 노드인 경우 패스
            continue;

        for(int i=0; i<graph[now].size(); i++) {
            int cost = dist + graph[now][i].second; // 거쳐서 가는 노드의 비용을 계산
                                                    // 현재노드까지 비용 + 다음 노드 비용
            if(cost < d[graph[now][i].first]) // 비용이 더 작다면 최단경로 테이블 값을 갱신.
            {
                d[graph[now][i].first] = cost;
                pq.push(make_pair(-cost,graph[now][i].first));
            }
        }
    }
}


int main() {
    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, m;
    cin >> n >> m;

    for(int i = 0; i < m; i++) {
        int source, destination, cost;
        cin >> source >> destination >> cost;
        graph[source].push_back({destination, cost});
    }

    for(int i = 1; i <= n; i++) {
        d[i] = INF;
    }

    int start, end;
    cin >> start >> end;
    dijkstra(start);

    cout << d[end];
}
728x90
Comments