๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/Programmers

[C++/PGS] Lv.3 : ํ•ฉ์Šน ํƒ์‹œ ์š”๊ธˆ (BFS/๋‹ค์ต์ŠคํŠธ๋ผ)

by xxilliant 2025. 5. 24.
728x90
๋ฐ˜์‘ํ˜•

 

https://school.programmers.co.kr/learn/courses/30/lessons/72413

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr


ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ ˆ๋ฒจ 3

bfs๋กœ ์ตœ์†Œ๊ฒฝ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ๊ฑด ์•Œ๊ฒ ๋Š”๋ฐ,

ํ•ฉ์Šน ๊ฒฝ๋กœ(S~p) + ํ•ฉ์Šน์ง€์ ๋ถ€ํ„ฐ A๊นŒ์ง€ + ํ•ฉ์Šน์ง€์ ๋ถ€ํ„ฐ B๊นŒ์ง€์˜ ํ•ฉ์˜ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•ด์•ผ ํ•˜๋‹ˆ

S~A, S~B์˜ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•˜๊ณ , ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์„ ๋นผ๋ฉด ๋˜๋Š”๊ฑด๊ฐ€? ์‹ถ์—ˆ๋‹ค.

ํ•˜์ง€๋งŒ ๋ญ”๊ฐ€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์•„์„œ,,,, ํžŒํŠธ๋ฅผ ์ฐธ์กฐํ–ˆ๋‹ค ใ…Žใ…Ž

 

์•Œ๊ณ  ๋ณด๋‹ˆ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด์„œ, [ S~p + A~p + B~p ] ๊ฑฐ๋ฆฌ์˜ ์ตœ์†Œํ•ฉ์„ ๊ตฌํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์˜€๋‹ค!

S,A,B๋ถ€ํ„ฐ ์ถœ๋ฐœํ•ด์„œ ๋ชจ๋“  ์ ์— ๋Œ€ํ•œ ์ตœ์†Œ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ ๋‹ค์Œ,

๊ฑฐ๋ฆฌ์˜ ํ•ฉ์ด ์ตœ์†Œ๊ฐ€ ๋˜๋Š” ์ง€์ ์„ ๊ตฌํ•˜๋ฉด ๋‹ต์ด ๋‚˜์˜จ๋‹ค.

 

์•„์ด๋””์–ด ๋– ์˜ฌ๋ฆฌ๋Š”๊ฒŒ ์–ด๋ ต์ง€๋งŒ, ๊ตฌํ˜„์€ ๊ฐ€์ค‘์น˜ ๊ฐฑ์‹ ๋งŒ ์‹ ๊ฒฝ์จ์ฃผ๋ฉด ๋œ๋‹ค.

 

 

๋‚˜์˜ ํ’€์ด

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

vector<vector<pair<int,int>>> graph(201);

vector<int> bfs(int start){
    priority_queue< pair<int,int>, vector<pair<int,int>>, greater<> > pq;
    // ๊ฐ€์ค‘์น˜(์šฐ์„ ์ˆœ์œ„ ๋‚ด๋ฆผ์ฐจ์ˆœ), ๋…ธ๋“œ
    vector<int> road(201,INT_MAX);
    pq.push({0,start});
    road[start] = 0;
    while(!pq.empty()){
        pair<int,int> p = pq.top();
        pq.pop();
        int nowNode = p.second;
        int nowCost = p.first;
        if(road[nowNode] < nowCost) continue;
        for(auto g:graph[nowNode]){
            if(g.first == start) continue;
            if(road[g.first] > g.second+nowCost){
                road[g.first] = g.second+nowCost;
                pq.push({road[g.first], g.first});
            }
        }
    }
    return road;
}

int solution(int n, int s, int a, int b, vector<vector<int>> fares) {
    int answer = INT_MAX;
    // ์ตœ์†Œ๋น„์šฉ ํƒ์ƒ‰ => ํ•ฉ์Šน ๊ฒฝ๋กœ(S~p) + ํ•ฉ์Šน์ง€์ ~A + ํ•ฉ์Šน์ง€์ ~B
    // ์ด ๋ง์€ ์ฆ‰, S~p + A~p + B~p ์˜ ์ตœ์†Œํ•ฉ.
    for(auto f: fares){
        int from = f[0];
        int to = f[1];
        int cost = f[2];
        graph[from].push_back({to, cost});
        graph[to].push_back({from, cost});
        // idx ์ถœ๋ฐœ, f1๋„์ฐฉ, ๊ฐ€์ค‘์น˜ f2
    }
    vector<int> s_road = bfs(s);
    vector<int> a_road = bfs(a);
    vector<int> b_road = bfs(b);
    
    for(int i=0; i<201; ++i){
        if(s_road[i]==INT_MAX || a_road[i]==INT_MAX || b_road[i]==INT_MAX)
            continue;
        if(answer > s_road[i]+a_road[i]+b_road[i])
            answer = s_road[i]+a_road[i]+b_road[i];
    }
    
    return answer;
}

728x90
๋ฐ˜์‘ํ˜•