๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 11779 ์ตœ์†Œ ๋น„์šฉ ๊ตฌํ•˜๊ธฐ2 dijkstra

by Jouureee 2021. 3. 10.

๋ฌธ์ œ :

www.acmicpc.net/problem/11779

 

11779๋ฒˆ: ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ 2

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ n(1≤n≤1,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ m(1≤m≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ m+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ ๋ฒ„์Šค

www.acmicpc.net

 

๋ถ„์„ :

์ด๋ฒˆ ๋ฌธ์ œ๋Š” ์ „ ๋ฌธ์ œ 1916๋ฒˆ

2021.03.10 - [Algorithm๐Ÿฐ/๋ฐฑ์ค€] - [๋ฐฑ์ค€] 1916 ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ dijkstra

์— ๊ฑฐ์ณ๊ฐ„ ๋…ธ๋“œ๋ฅผ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋„๋ก ์ถ”๊ฐ€ํ•˜๋Š” ์ž‘์—…์ด ํ•„์š”ํ•˜๋‹ค. 

๋”ฐ๋ผ์„œ while ๋ฌธ ์•ˆ for ๋ฌธ์— t ๋ฐฐ์—ด์„ ํ•˜๋‚˜ ์ถ”๊ฐ€ํ•ด ๊ทธ ์ „ ๋…ธ๋“œ๋ฅผ ์ธ๋ฑ์Šค ๊ฐ’์œผ๋กœ ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๊ณ 

๊ทธ ์ „ popํ•ด์˜จ ๋…ธ๋“œ(now)๋ฅผ ๊ฐ’์œผ๋กœ ๋ฐ›๋„๋ก ํ•˜์˜€๋‹ค.

์ถœ๋ ฅํ•  ๋•Œ์—๋Š” end์ธ๋ฑ์Šค๋ถ€ํ„ฐ route ๋ฒกํ„ฐ์— ๋‹ด๊ธด๋‹ค. ๊ทธ๋ž˜์„œ ์—ญ์ˆœ์œผ๋กœ ๋ฒกํ„ฐ๋ฅผ ์ถœ๋ ฅํ•ด๋„๋ก ํ•˜์˜€๋‹ค, 

 

 

c++ ์ฝ”๋“œ :

//
//  11779_min_cost2.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/03/10.
//

#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
#define INF 1e9

vector<pair<int, int>>vertex[1001];
int d[100001]; // ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”
int t[100001];

void min_bus(int start, int end){
    priority_queue<pair<int, int>>pq;
    pq.push(make_pair(0, start));
    d[start] = 0;
    while(!pq.empty()){
        int dist = -pq.top().first;
        int now = pq.top().second;
        pq.pop();
        
        for(int i = 0; i < vertex[now].size(); i++){
            
            int cost = dist + vertex[now][i].second;
            if(cost < d[vertex[now][i].first]) // ๋น„์šฉ์ด ๋” ์ž‘๋‹ค๋ฉด ์ตœ๋‹จ๊ฒฝ๋กœ ํ…Œ์ด๋ธ” ๊ฐ’์„ ๊ฐฑ์‹ .
            {
                d[vertex[now][i].first] = cost;
                t[vertex[now][i].first] = now; // ์ „ ๋…ธ๋“œ๊ฐ€ ๋ถ€๋ชจ ๋…ธ๋“œ ๊ฐ€์ง€๊ณ  ์žˆ๋„๋ก
                
                pq.push(make_pair(-cost,vertex[now][i].first));
            }
        }
    }
    
}

int main(){
    int city;
    cin >> city;
    int bus;
    cin >> bus;
    for(int i = 0 ; i < bus; i++){
        int in, to, cost;
        cin >> in >> to >> cost;
        vertex[in].push_back({to, cost});
    }
    
    int start, end;
    cin >> start >> end;
    fill(d, d+100001, INF);
    
    min_bus(start, end);
    cout << d[end] << '\n';
    
    vector<int>route;
    
    int temp_end = end;
    
    while (temp_end)
    {
        route.push_back(temp_end);
        temp_end = t[temp_end];
    }
    cout << route.size() << endl;
    for (int i = ((int)route.size()) - 1; i >= 0; i--) cout << route[i] << " ";
    cout << endl;

    return 0;
}

๋Œ“๊ธ€