티스토리 뷰
반응형
백준 1753번 최단경로
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


정답 코드
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int V, E;
int K;
int u, v, w;
int INF = 1000000;
vector<pair<int, int> > adj[20001];
int dist[20001];
void dijkstra(int src) {
dist[src] = 0;
priority_queue<pair<int, int> > pq;
pq.push(make_pair(0, src));
while (!pq.empty()) {
int cost = -pq.top().first;
int here = pq.top().second;
pq.pop();
if (dist[here] < cost) continue;
for (int i = 0; i < adj[here].size(); i++) {
int there = adj[here][i].first;
int nextDist = cost + adj[here][i].second;
if (dist[there] > nextDist) {
dist[there] = nextDist;
pq.push(make_pair(-nextDist, there));
}
}
}
}
int main(void)
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> V >> E;
cin >> K;
for (int i = 1; i <= V; i++) {
dist[i] = INF;
}
for (int i = 0; i < E; i++) {
cin >> u >> v >> w;
adj[u].push_back(make_pair(v, w));
}
dijkstra(K);
for (int i = 1; i <= V; i++) {
if (dist[i] == INF) {
cout << "INF" << endl;
}
else
cout << dist[i] << endl;
}
}
문제 풀이
다익스트라 알고리즘을 이용해서 풀 수 있는 문제입니다. 다익스트라 알고리즘은 최단경로를 구할 때 주로 이용하는 알고리즘입니다. 다익스트라 알고리즘은 여기를 누르시면 더 자세히 볼 수 있습니다. 다익스트라 알고리즘도 정석적인 풀이가 있으니 한 번 공부하시고 나서 풀어보시면 좋을 것 같습니다.
반응형
'Algorithm > BOJ' 카테고리의 다른 글
백준 1780번 C++ (0) | 2023.07.26 |
---|---|
백준 1764번 C++ (0) | 2023.07.25 |
백준 1748번 C++ (0) | 2023.07.25 |
백준 1747번 C++ (0) | 2023.07.25 |
백준 1735번 C++ (0) | 2023.07.25 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Do it!
- C++ Stack
- 백준
- c++ string
- 자료구조
- 알고리즘 공부
- 자바
- BFS
- 반복문
- DP
- 유클리드 호제법
- DFS
- 투 포인터
- html
- 유니온 파인드
- 스택
- js
- java
- 카운팅 정렬
- 자바스크립트
- 세그먼트 트리
- CSS
- C++
- 스프링 부트 crud 게시판 구현
- 이분 매칭
- 우선순위 큐
- 백준 풀이
- 알고리즘
- 에라토스테네스의 체
- HTML5
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함