[프로그래머스/C++] 배달

1 분 소요

1.문제 링크

배달



2. 풀이 전 계획과 생각

  • 최단경로 알고리즘 다익스트라 이용하기



3. 풀이

#include <iostream>
#include <vector>
#include <map>
#define INF 1e9 // 무한을 의미하는 값으로 10억을 설정
using namespace std;

// 각 노드에 연결되어 있는 노드를 담는 배열
vector<pair<int,int> > graph[51];
// 방문한 적이 있는지 체크하는 목적의 배열 만들기
bool visited[51];
// 최단 거리 테이블 만들기
int d[51];

// 방문하지 않은 노드 중에서, 가장 최단 거리가 짧은 노드의 번호를 반환
int getSmallestNode(int n) {
    int min_value = INF;
    int index = 0; // 가장 최단 거리가 짧은 노드
    for (int i = 1; i <= n; i++) {
        if (d[i] < min_value && !visited[i]) {
            min_value = d[i];
            index = i;
        }
    }
    return index;
}

// 다익스트라 알고리즘
void dijkstra(int start, int n) {
    d[start] = 0;
    visited[start] = true;
    for (int j = 0; j < graph[start].size(); j++) {
        d[graph[start][j].first] = graph[start][j].second;
    }
    // 시작 노드를 제외한 전체 n - 1개의 노드에 대해 반복
    for (int i = 0; i < n - 1; i++) {
        // 현재 최단 거리가 가장 짧은 노드를 꺼내서, 방문 처리
        int now = getSmallestNode(n);
        visited[now] = true;
        // 현재 노드와 연결된 다른 노드를 확인
        for (int j = 0; j < graph[now].size(); j++) {
            int cost = d[now] + graph[now][j].second;
            // 현재 노드를 거쳐서 다른 노드로 이동하는 거리가 더 짧은 경우
            if (cost < d[graph[now][j].first]) {
                d[graph[now][j].first] = cost;
            }
        }
    }
}

int solution(int N, vector<vector<int> > road, int K) {
    fill_n(d,51,INF);
    fill_n(visited,51,false);

    map<pair<int,int>,int> m;
    for(int i=0;i<road.size();i++){
        int cost = road[i][2];
        int x = min(road[i][0], road[i][1]);
        int y = max(road[i][0], road[i][1]);
        if(m.find({x,y})!=m.end()){
            int c = m[{x,y}];
            if(c>cost) m[{x,y}]=cost;
        }
        else {
            m.insert({ {x, y}, cost} );
        }
    }
    map<pair<int,int>,int>::iterator iter;
    for(iter = m.begin(); iter!=m.end(); iter++){
        graph[(*iter).first.first].push_back({(*iter).first.second, (*iter).second});
        graph[(*iter).first.second].push_back({(*iter).first.first, (*iter).second});
    }

    dijkstra(1,N);

    int answer = 0;
    for(int i=1;i<=N;i++) cout<<d[i]<<' ';
    for(int i=1;i<=N;i++){
        if(d[i]<=K) answer++;
    }

    return answer;
}

입력으로 중복된 노드들이 들어올 수 있다. 그래서 map 자료형을 사용했고, 만약 이미 map에 저장된 노드쌍이라면 cost를 비교해서 더 작은 cost로 저장한다.

그 후 map을 기반으로 vector에 삽입해 다익스트라 알고리즘을 사용한다.



4. 풀이하면서 고민했던 점

  • graph에 push_back 할때 양쪽 모두 삽입해야함. 노드1,2가 cost 5로 연결되있다면, (1,2,5)와 (2,1,5) 이런식으로 노드를 바꿔서 두번 삽입해 줘야함.



5. 문제를 풀고 알게된 개념 및 소감

  • 다익스트라 알고리즘을 복습할 수 있어서 유익했음.