https://www.acmicpc.net/problem/1446
1446번: 지름길
첫째 줄에 지름길의 개수 N과 고속도로의 길이 D가 주어진다. N은 12 이하인 양의 정수이고, D는 10,000보다 작거나 같은 자연수이다. 다음 N개의 줄에 지름길의 시작 위치, 도착 위치, 지름길의 길이
www.acmicpc.net
과정
- 0부터 시작해서 지름길이 있는지 확인한다.
- 지름길이 있으면 이전에 방문한 기록과 비교하여 더 빠르게 도달하는지 확인한다.
- 없다면 1칸씩 이동하며 진행한다.
코드
#include<iostream>
#include<queue>
using namespace std;
int N,D;
vector<pair<int, int> > ways[10001];
int chk[10001];
void input(){
cin>>N>>D;
int a,b,c;
while(N--){
cin>>a>>b>>c;
ways[a].push_back({b,c});
}
}
int bfs(){
priority_queue<pair<int, int> > pq;
pq.push({0,0});
chk[0] = 0;
while(!pq.empty()){
int cost = -pq.top().first;
int node = pq.top().second;
pq.pop();
if(node == D)
return cost;
if(chk[node] < cost)
continue;
for(int i=0;i<ways[node].size();++i){
int ncost = ways[node][i].second + cost;
int next = ways[node][i].first;
if(chk[next] <= ncost || next > D)
continue;
chk[next] = ncost;
pq.push({-ncost, next});
}
if(cost + 1 <= chk[node + 1]){
chk[node + 1] = cost + 1;
pq.push({-(cost +1), node + 1});
}
}
return -1;
}
void solution(){
fill(&chk[0], &chk[10001], 987'654'321);
cout<<bfs()<<'\n';
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
input();
solution();
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| 17266 - 어두운 굴다리 (0) | 2023.07.15 |
|---|---|
| 2179 - 비슷한 단어 (0) | 2023.07.14 |
| 19942 - 다이어트 (0) | 2023.07.13 |
| 19949 - 영재의 시험 (0) | 2023.07.13 |
| 19591 - 독특한 계산기 (0) | 2023.07.13 |
댓글