https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
vector<pair<int, int>> bus[1001];
int start,dest;
int check[1001];
void Dijkstra(){
priority_queue<pair<int, int>> pq;
pq.push(make_pair(0,start));
check[start]=0;
while(!pq.empty()){
int sum=pq.top().first;
int now=pq.top().second;
pq.pop();
if(check[now]<sum)
continue;
for(int i=0;i<bus[now].size();i++){
int nextDest=bus[now][i].first;
int nextSum=sum+bus[now][i].second;
if(check[nextDest]>nextSum){
check[nextDest]=nextSum;
pq.push(make_pair(nextSum,nextDest));
}
}
}
cout<<check[dest]<<endl;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int n,m;
cin>>n>>m;
memset(check, 98765432, sizeof(check));
for(int i=0;i<m;i++){
int tmpS,tmpD,tmpM;
cin>>tmpS>>tmpD>>tmpM;
bus[tmpS].push_back(make_pair(tmpD,tmpM));
}
cin>>start>>dest;
Dijkstra();
return 0;
}
우선순위 큐 사용
: priority_queue<pair<int, int>> pq; 일때는 앞의 인자를 기준으로 우선순위가 적용된다.
'알고리즘' 카테고리의 다른 글
[C++] 백준 11779번 : 최소비용 구하기2 (0) | 2024.01.02 |
---|---|
[C++] 백준 1753번 : 최단경로 (0) | 2023.12.27 |
[C++] 백준 15651번 : N과 M(3) (0) | 2023.11.24 |
[C++] 백준 11729번 : 하노이 탑 이동 순서 (0) | 2023.11.23 |
[C++] 백준 9663번 : N-Queen (0) | 2023.11.23 |