알고리즘
[C++] 백준 1753번 : 최단경로
88dldl
2023. 12. 27. 01:08
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 <vector>
#include <queue>
#define INF 987654321
using namespace std;
int v,e,start;
vector<pair<int,int>> road[200001];
int check[200001];
void Dijkstra(){
priority_queue<pair<int,int>> pq;
pq.push(make_pair(0,start));
check[start]=0;
while(!pq.empty()){
int tmpsum=-pq.top().first;
int now=pq.top().second;
pq.pop();
if(check[now]<tmpsum)
continue;
for(int i=0;i<road[now].size();i++){
int nextDest=road[now][i].first;
int nextSum=tmpsum+road[now][i].second;
if(check[nextDest]>nextSum){
check[nextDest]=nextSum;
pq.push(make_pair(-nextSum,nextDest));
}
}
}
for(int i=1;i<=v;i++){
if(check[i]==INF) cout<<"INF\n";
else cout<<check[i]<<"\n";
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>v>>e>>start;
for(int i=0;i<e;i++){
int a,b,c;
cin>>a>>b>>c;
road[a].push_back(make_pair(b,c));
}
for(int i=1;i<=v;i++){
check[i]=INF;
}
Dijkstra();
return 0;
}
아래의 1916번에서는 음수화를 시키지 않고 그냥 코드를 작성했는데, 이 문제에서 그렇게 작성하니 시간초과가 떴다!
=> 음수화를 통해 우선순위큐의 특성을 더 활용하여 시간초과를 해결했다.
비슷한 문제
[C++] 백준 1916번 : 최소비용 구하기
https://www.acmicpc.net/problem/1916 1916번: 최소비용 구하기 첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다
88dldl.tistory.com