BOJ_최소비용 구하기_1916

융바오·2024년 12월 20일

Problem Solving

목록 보기
10/89

문제 링크

성능 요약

Java - 메모리: 50504 KB, 시간: 392 ms
C++ - 메모리: 4688 KB, 시간: 96 ms

분류

데이크스트라, 그래프 이론, 최단 경로

제출 일자

2024년 12월 20일 22:15:43

문제 설명

N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.

입력

첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다. 버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다.

그리고 M+3째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다. 출발점에서 도착점을 갈 수 있는 경우만 입력으로 주어진다.

출력

첫째 줄에 출발 도시에서 도착 도시까지 가는데 드는 최소 비용을 출력한다.

풀이

느낀점

  • 다익스트라는 List[] 와 dp테이블 하나를 두고 우선순위큐를 통해 최솟값을 갱신하면서 구하는걸 베이스로 하자.

설계 : 5분

  • 입력된 버스정보를 각 도시에 대한 인접리스트로 생성한다.
  • 시작점과 끝점을 알았다면 우선순위큐에 시작점을 넣고 다익스트라를 시작한다.
  • 다익스트라는 계속해서 갱신되는 최솟값을 기준으로 방문체크를 할 수 있으므로, visited 배열은 필요없다.
  • 대신 최솟값을 갱신하는 기준으로만 큐에 추가할 수 있도록 해야한다.

코드(Java)

  • 구현 시간: 30분
/**
 * Author: yngbao97, Yuk Yejin
 * Problem: 최소비용 구하기_1916
 * Date: 2024.12.18
 */

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;

    @SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {

		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
        int m = Integer.parseInt(br.readLine());

        List<City>[] adj = new List[n+1];
        int[] dist = new int[n+1];
        for (int i = 0; i <= n; i++) {
            adj[i] = new ArrayList<>();
            dist[i] = Integer.MAX_VALUE;
        }

        for (int i = 0; i < m; i++) {
            st = new StringTokenizer(br.readLine(), " ");
            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            adj[start].add(new City(end, cost));
        }

        String[] input = br.readLine().split(" ");
        int start = Integer.parseInt(input[0]);
        int dest = Integer.parseInt(input[1]);

        PriorityQueue<City> pq = new PriorityQueue<>();
        pq.add(new City(start, 0));
        dist[start] = 0;
        int answer = 0;

        while (!pq.isEmpty()) {

            City curr = pq.poll();
            if (curr.num == dest) {
                answer = curr.dist;
                break;
            }

            for (City city : adj[curr.num]) {
                if (dist[city.num] > curr.dist + city.dist) {
                    dist[city.num] = curr.dist + city.dist;
                    pq.add(new City(city.num, dist[city.num]));
                }
            }
        }

        bw.write(String.valueOf(answer));
		
		bw.flush();
		bw.close();
		br.close();
	}
}

class City implements Comparable<City> {
    int num;
    int dist;

    City () {}
    City (int num, int dist) {
        this.num = num;
        this.dist = dist;
    }

    @Override
    public int compareTo(City o) {
        return Integer.compare(this.dist, o.dist);
    }
}

코드(C++)

  • 구현 시간: 40분
/**
 * Author: yngbao97, Yuk Yejin
 * Problem: 최소비용 구하기_1916
 * Date: 2024.12.20
 */

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <climits>
#include <queue>
using namespace std;

class City {
    public:
        int num, dist;

        City () : num(-1), dist(INT_MAX) {}
        City (int a, int b) : num(a), dist(b) {}
};

struct compareDist {
    bool operator() (const City& c1, const City& c2) {
        return c1.dist > c2.dist;
    }
};

int main() {

    int n, m;
    cin >> n >> m;
    cin.ignore();

    vector<vector<City> > adj(n+1);
    
    for (int i = 0; i < m; i++) {
        string input;
        getline(cin, input);
        stringstream ss(input);
        int start, end, dist;
        ss >> start >> end >> dist;
        adj[start].push_back(City(end, dist));
    }

    int start, end;
    cin >> start >> end;

    vector<int> dp(n+1);
    fill(dp.begin(), dp.end(), INT_MAX);
    priority_queue<City, vector<City>, compareDist> pq;
    pq.push(City(start, 0));
    dp[start] = 0;

    while(!pq.empty()) {

        City curr = pq.top();
        pq.pop();

        if (curr.num == end) break;

        for (City city : adj[curr.num]) {
            if (dp[city.num] > curr.dist + city.dist) {
                dp[city.num] = curr.dist + city.dist;
                pq.push(City(city.num, dp[city.num]));
            }
        }
    }

    cout << dp[end];

    return 0;
}
  • 알게된 점
    • int 형 최대값은 헤더를 include하면 INT_MAX로 값을 가져올 수 있다.
    • 인접행렬말고 무조건 인접 리스트 사용! 두개의 값으로 요소를 비교하고 사용할 수 있을때에는 pair 사용을 고려해봐도 좋다.

0개의 댓글