티스토리 뷰
https://programmers.co.kr/learn/courses/30/lessons/12978
코딩테스트 연습 - 배달
5 [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] 3 4 6 [[1,2,1],[1,3,2],[2,3,2],[3,4,3],[3,5,2],[3,5,3],[5,6,1]] 4 4
programmers.co.kr
한 정점에서 모든 정점으로 가는 최단거리를 구하기 위해 다익스트라(Dijkstra) 알고리즘을 사용해 풀이하였습니다.
O(logN)의 힙 구조를 가진 우선순위 큐를 사용하여 다익스트라 알고리즘을 구현하였습니다.
C++ 소스 코드
#include <vector>
#include <queue>
#define MAX 10000000
using namespace std;
int res[51];
vector<pair<int, int> > adj[51];
int solution(int N, vector<vector<int> > road, int K) {
int answer = 0;
fill(&res[0],&res[50]+1,MAX);
priority_queue<pair<int, int> > pq;
for(int i=0;i<road.size();i++){
adj[road[i][0]].push_back(make_pair(road[i][1],road[i][2]));
adj[road[i][1]].push_back(make_pair(road[i][0],road[i][2]));
}
res[1]=0;
pq.push(make_pair(0,1));
while(!pq.empty()){
int now = pq.top().second;
int dist = -pq.top().first;
pq.pop();
if (dist > res[now]) continue;
for(int i=0;i<adj[now].size();i++){
int next= adj[now][i].first;
int nextDist = dist + adj[now][i].second;
if(nextDist < res[next]){
res[next] = nextDist;
pq.push(make_pair(-nextDist,next));
}
}
}
for(int i=1;i<=N;i++){
if (res[i]<=K) answer++;
}
return answer;
}
'Algorithm > 알고리즘 문제풀이' 카테고리의 다른 글
프로그래머스) Lv3 - 하노이의 탑 (0) | 2020.07.25 |
---|---|
프로그래머스) Lv3 - 행렬의 곱셈 (0) | 2020.07.19 |
BOJ) 15732 - 도토리 숨기기 (0) | 2020.07.13 |
BOJ) 16973 - 직사각형 탈출 (0) | 2020.07.09 |
프로그래머스) Lv1 - 체육복 (0) | 2020.07.09 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준온라인저지
- coreml
- Kotlin
- blendshape
- 백준
- cocoapods
- Swift
- Swift unowned
- Swift weak
- rxswift
- 코코아팟
- C++
- SwiftUI
- Lottie
- UIHostingController
- 안드로이드
- GraphDB
- infallible
- ARKit
- DispatchQueue
- ios
- 알고리즘
- disposeBag
- Reactivex
- 카카오인턴십
- SWEA
- boj
- rxswift6
- blendshapes
- 프로그래머스
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
글 보관함