728x90
반응형
https://www.acmicpc.net/problem/1504
1504번: 특정한 최단 경로
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존
www.acmicpc.net
#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;
int N, E, V1, V2, Cnt;
map<int, vector<pair<int, int>>> m;
vector<int> Dist, SaveDist;
void Dijkstra(int start)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({ 0, start });
Dist[start] = 0;
while (!pq.empty())
{
int c = pq.top().first;
int n = pq.top().second;
pq.pop();
for (const auto& i : m[n])
{
if (Dist[i.first] > c + i.second)
{
Dist[i.first] = c + i.second;
pq.push({ Dist[i.first], i.first });
}
}
}
}
void Clear()
{
Dist.clear();
Dist.resize(N + 1, 987654321);
}
bool Assert()
{
if (Cnt >= 987654321)
{
Cnt = 987654321;
return true;
}
return false;
}
void Func(int v1, int v2)
{
Cnt += Dist[v1];
if (Assert()) return;
Clear();
Dijkstra(v1);
Cnt += Dist[v2];
if (Assert()) return;
Clear();
Dijkstra(v2);
Cnt += Dist[N];
if (Assert()) return;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> E;
Dist.resize(N + 1, 987654321);
for (int i = 0, a, b, c; i < E; ++i)
{
cin >> a >> b >> c;
m[a].push_back({ b, c });
m[b].push_back({ a, c });
}
cin >> V1 >> V2;
Dijkstra(1);
SaveDist = Dist;
Func(V1, V2);
int save = Cnt;
Cnt = 0;
Dist = SaveDist;
Func(V2, V1);
if (save == 987654321 && Cnt == 987654321) cout << -1 << "\n";
else cout << min(save, Cnt) << "\n";
}
1 -> v1 -> v2와 1 -> v2 -> v1 중 최솟값을 출력한다.
728x90
반응형
'📕알고리즘 문제 > 📝Baekjoon' 카테고리의 다른 글
[백준] 실버1 : (11659) 구간 합 구하기 5 (0) | 2024.10.03 |
---|---|
[백준] 실버1 : (1932) 정수 삼각형 (0) | 2024.04.18 |
[백준] 실버2 : (2512) 예산 (0) | 2024.04.16 |
[백준] 골드3 : (1238) 파티 (0) | 2024.04.12 |
[백준] 실버2 : (11724) 연결 요소의 개수 (0) | 2024.04.11 |