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;
}
'๐ ์๊ณ ๋ฆฌ์ฆ > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++/PGS] Lv.1 : ํ๋ฐฐ ์์ ๊บผ๋ด๊ธฐ (0) | 2025.06.04 |
---|---|
[C++/PGS] Lv.2 : ์ซ์ ๋ณํํ๊ธฐ (0) | 2025.05.31 |
[C++/PGS] Lv.2 : ๋ชจ์์ฌ์ (0) | 2025.05.24 |
[C++/PGS] Lv.1 : ๊ฐ์ ์ซ์๋ ์ซ์ด (Stack) (0) | 2025.05.24 |
[C++/PGS] Lv.2 : ๋ค์ ์๋ ํฐ ์ ์ฐพ๊ธฐ (0) | 2025.05.15 |