
https://www.acmicpc.net/problem/1753
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가
www.acmicpc.net
문제 풀이
출발점이 명시된 최소 간선 찾기 문제이므로 다익스트라를 이용해 문제를 해결했다.
다익스트라 설명은 이전 문제에 설명했으므로 생략한다.
https://itcodeheaven.tistory.com/87
[백준] 1916번 최소비용 구하기 C++ 문제풀이
https://www.acmicpc.net/problem/1916 1916번: 최소비용 구하기 첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다
itcodeheaven.tistory.com
소스 코드
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int INF = 1000000001;
vector<pair<int, int>> edge[20001];
int d[20001] = { 0 };
void dijkstra(int start) {
d[start] = 0;
priority_queue<pair<int, int>> pq;
pq.push(make_pair(0, start));
while (!pq.empty()) {
int weight = -pq.top().first;
int current = pq.top().second;
pq.pop();
//이부분 까먹음
if (d[current] != weight)
continue;
else {
for (int i = 0; i < edge[current].size(); i++) {
int next = edge[current][i].first;
int next_w = weight + edge[current][i].second;
if (d[next] > next_w) {
d[next] = next_w;
pq.push(make_pair(-next_w, next));
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int v, e, st;
cin >> v >> e >> st;
//거리 초기화
for (int i = 1; i <= v; i++) {
d[i] = INF;
}
//간선 정보 추가
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
edge[a].push_back(make_pair(b, c));
}
dijkstra(st);
for (int i = 1; i <= v; i++) {
if (d[i] == INF)
cout << "INF" << '\n';
else
cout << d[i] << '\n';
}
}
'알고리즘' 카테고리의 다른 글
[프로그래머스] 두 원 사이의 정수 쌍 C++ 문제풀이 (0) | 2024.02.22 |
---|---|
[프로그래머스] 달리기 경주 C++ 문제풀이 (0) | 2024.02.13 |
[백준] 1916번 최소비용 구하기 C++ 문제풀이 (0) | 2024.02.04 |
[백준] 16236번 아기 상어 C++ 문제풀이 (1) | 2024.02.02 |
[백준] 1766번 문제집 C++ 문제풀이 (0) | 2024.01.28 |