while(1) 작심삼일();

[백준 1916번] 최소비용 구하기 본문

CS/baekjoon

[백준 1916번] 최소비용 구하기

hanjongho 2021. 2. 17. 17:00

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

 

1916번: 최소비용 구하기

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

www.acmicpc.net

풀이)

자원 측면에서 vector를 사용하였고, 특정 노드에 방문했을 때 갈 수 있는 노드들을 거리가 최소가 된다면 갱신하는 방식으로 구현하였다. 

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
 
int N, M, start, finish;
int dist[1001];
vector <pair<int,int> > graph[1001];
queue<int> q;

int dijkstra(int start) {
    q.push(start);
    dist[start] = 0;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (int i = 0; i < graph[x].size(); i++) {
            int nx = graph[x][i].first;
            int cost = graph[x][i].second;
            if (dist[nx] == -1 || dist[x] + cost < dist[nx]) {
                dist[nx] = dist[x] + cost;
                if(nx != finish)
                    q.push(nx);
            }
        }
    }
    return dist[finish];
}
 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    memset(dist, -1, sizeof(dist));
    cin >> N >> M;
 
    while (M--){
        int b, c, d;
        cin >> b >> c >> d;
        graph[b].push_back(make_pair(c, d));
    }
    cin >> start >> finish;
    cout << dijkstra(start) << "\n";
    return (0);
}

 

 

제 코드는 절대 완벽하지 않습니다

더 좋은 풀이방법 혹은 코드에 관한 질문이 있으시면 언제든 댓글주세요!

'CS > baekjoon' 카테고리의 다른 글

[백준 3190번] 뱀  (0) 2021.02.18
[백준 2170번] 선 긋기  (0) 2021.02.17
[백준 1759번] 암호 만들기  (0) 2021.02.16
[백준 1753번] 최단경로  (0) 2021.02.16
[백준 14891번] 톱니바퀴  (0) 2021.02.10
Comments