Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Unreal Engine 5
- 트리
- 그래프
- 우선순위 큐
- 브루트포스
- c++
- XR Interaction Toolkit
- Team Fortress 2
- 수학
- 누적 합
- 재귀
- 자료구조
- 시뮬레이션
- 정렬
- 알고리즘
- 유니온 파인드
- 다익스트라
- 스택
- ue5
- 그리디 알고리즘
- 백준
- 투 포인터
- 문자열
- 유니티
- 다이나믹 프로그래밍
- DFS
- 구현
- BFS
- VR
- 백트래킹
Archives
- Today
- Total
1일1알
백준 1504번 특정한 최단 경로 C++ 본문
다익스트라를 이용해서
(1~v1) + (v1~v2) + (v2~n) 과 (1~v2) + (v2~v1) + (v1~n) 중 경로가 작은 값을 출력했다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, e;
vector<vector<int>> vertexs;
struct VertexCost {
bool operator<(const VertexCost& other) const {
return cost < other.cost;
}
bool operator>(const VertexCost& other) const {
return cost > other.cost;
}
int vertex;
int cost;
};
int Dijikstra(int start, int end) {
vector<int> best(n + 1, INT_MAX);
priority_queue<VertexCost, vector<VertexCost>, greater<VertexCost>> pq;
pq.push({ start,0 });
best[start] = 0;
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
if (curr.cost > best[curr.vertex])
continue;
for (int i = 1; i <= n; i++) {
if (vertexs[curr.vertex][i] == -1)
continue;
int nextCost = curr.cost + vertexs[curr.vertex][i];
if (nextCost >= best[i])
continue;
best[i] = nextCost;
pq.push({ i,nextCost });
}
}
return best[end];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> e;
vertexs = vector<vector<int>>(n + 1, vector<int>(n + 1, -1));
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
vertexs[a][b] = c;
vertexs[b][a] = c;
}
int v1, v2;
cin >> v1 >> v2;
int startTov1 = Dijikstra(1, v1);
int startTov2 = Dijikstra(1, v2);
int v1Tov2 = Dijikstra(v1, v2);
int v1Ton = Dijikstra(v1, n);
int v2Ton = Dijikstra(v2, n);
int dist1 = INT_MAX;
int dist2 = INT_MAX;
if (startTov1 != INT_MAX && v1Tov2 != INT_MAX && v2Ton != INT_MAX) {
dist1 = startTov1 + v1Tov2 + v2Ton;
}
if (startTov2 != INT_MAX && v1Tov2 != INT_MAX && v1Ton != INT_MAX) {
dist2 = startTov2 + v1Tov2 + v1Ton;
}
if (dist1 == INT_MAX && dist2 == INT_MAX) {
cout << -1;
}
else {
cout << min(dist1, dist2);
}
};
'알고리즘' 카테고리의 다른 글
백준 1967번 트리의 지름 C++ (0) | 2022.06.17 |
---|---|
백준 1753번 최단경로 C++ (0) | 2022.06.16 |
백준 5639번 이진 검색 트리 C++ (0) | 2022.06.14 |
백준 1916번 최소비용 구하기 C++ (0) | 2022.06.13 |
백준 1991번 트리 순회 C++ (0) | 2022.06.12 |