๋ฌธ์
์ฝ๋
#include <iostream>
#include <queue>
#include <algorithm>
#define INF 1e9 //๋ฌดํ๋๋ฅผ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
using namespace std;
int N, E, v1, v2; //N=์ ์ ์ ๊ฐ์, E=๊ฐ์ ์ ๊ฐ์, v1,v2=๊ฑฐ์ณ์ผ ํ๋ ์ ์ ๋ฒํธ
vector<pair<int, int>>graph[801]; //๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฐฐ์ด
int d[801]; //์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ
int check[801]; //v1,v2๋ฅผ ๊ฑฐ์ณ ๊ฐ๋ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ฅํ๋ ํ
์ด๋ธ
void reset() {
fill(d, d + 801, INF);
}
void dijkstra(int start) {
reset();
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq; //์ต์ํ
pq.push({ 0,start }); //์์ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ๋น์ฉ์ 0์ผ๋ก ์ค์ ํ์ฌ ํ์ ์ฝ์
.
d[start] = 0;
while (!pq.empty()) {
int dist = pq.top().first;
int now = pq.top().second;
pq.pop();
if (d[now] < dist) continue; //์ด๋ฏธ ์ฒ๋ฆฌ๋ ์ ์ด ์๋ ๋
ธ๋๋ผ๋ฉด ๋ฌด์
for (int i = 0; i < graph[now].size(); i++) {
int neighbor = graph[now][i].first;
int neighborDist = dist + graph[now][i].second;
if (neighborDist < d[neighbor]) {
d[neighbor] = neighborDist;
pq.push({ neighborDist,neighbor });
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> N >> E;
for (int i = 0; i < E; i++) {
int a, b, c; cin >> a >> b >> c;
graph[a].push_back({ b,c }); //a์์b๋ก ๊ฐ๋๋ฐ c๋งํผ์ ๋น์ฉ์ด ๋ ๋ค.
graph[b].push_back({ a,c }); //์๋ฐฉํฅ ์ฒ๋ฆฌ
}
cin >> v1 >> v2;
/* ๊ณ ๋ ค ํด์ผ ํ ๊ฒฝ์ฐ์ ์
1. a->v1->v2->b
2. a->v2->v1->b
*/
dijkstra(1);
check[0] = d[v1]; //1->v1๊น์ง์ ๊ฑฐ๋ฆฌ
check[1] = d[v2]; //1->v2๊น์ง์ ๊ฑฐ๋ฆฌ
dijkstra(v1);
check[2] = d[v2]; //v1->v2๊น์ง์ ๊ฑฐ๋ฆฌ
check[3] = d[N]; //v1->N๊น์ง์ ๊ฑฐ๋ฆฌ
dijkstra(v2);
check[4] = d[N]; //v2->N๊น์ง์ ๊ฑฐ๋ฆฌ
check[5] = d[v1]; //v2->v1๊น์ง์ ๊ฑฐ๋ฆฌ
int ans = INF;
ans = min(ans, check[0] + check[2] + check[4]); //v1->v2
ans = min(ans, check[1] + check[5] + check[3]); //v2->v1
if (ans == INF || check[2] == INF || check[5] == INF) cout << -1;
else cout << ans;
}
'Algorithm ๐ง๐ปโ๐ป > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค,c++] 1547๋ฒ - ๊ณต (0) | 2021.11.17 |
---|---|
[๋ฐฑ์ค,c++] 1541๋ฒ - ์์ด๋ฒ๋ฆฐ ๊ดํธ (0) | 2021.11.17 |
[๋ฐฑ์ค,c++] 15240๋ฒ - Paint bucket (0) | 2021.11.17 |
[๋ฐฑ์ค,c++] 14950๋ฒ - ์ ๋ณต์ (0) | 2021.11.14 |
[๋ฐฑ์ค,c++] 14938๋ฒ - ์๊ฐ๊ทธ๋ผ์ด๋ (0) | 2021.11.14 |
[๋ฐฑ์ค,c++] 1439๋ฒ - ๋ค์ง๊ธฐ (0) | 2021.11.14 |
๋๊ธ