250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(프로그래머스 c++)배달 본문
728x90
반응형
programmers.co.kr/learn/courses/30/lessons/12978
다익스트라를 이용하여 1에서 거리가 K 이하인 마을의 수를 구할 수 있다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int solution(int N, vector<vector<int> > road, int K) {
int answer = 0;
vector<pair<int, int>> graph[51];
priority_queue<pair<int, int>> pq;
vector<int> dist(51, 999999);
for(int i = 0; i < road.size(); i++){
int a, b, c;
a = road[i][0];
b = road[i][1];
c = road[i][2];
graph[a].push_back(make_pair(b, c));
graph[b].push_back(make_pair(a, c));
}
pq.push(make_pair(1, 0));
dist[1] = 0;
while(!pq.empty()){
int current = pq.top().first;
int cost = -pq.top().second;
pq.pop();
for(int i = 0; i < graph[current].size(); i++){
int next = graph[current][i].first;
int nextCost = graph[current][i].second;
if(dist[next] > dist[current] + nextCost){
dist[next] = dist[current] + nextCost;
pq.push(make_pair(next, -dist[next]));
}
}
}
for(int i = 1; i <= N; i++){
if(dist[i] <= K){
answer++;
}
}
return answer;
}
728x90
반응형
'프로그래머스 알고리즘 > 2단계' 카테고리의 다른 글
(프로그래머스 JS)다리를 지나는 트럭 (0) | 2021.03.09 |
---|---|
(프로그래머스 JS)프린터 (0) | 2021.03.09 |
(프로그래머스 c++)게임 맵 최단거리 (0) | 2021.03.04 |
(프로그래머스 c++)이진 변환 반복하기 (0) | 2020.11.23 |
(프로그래머스 c++)쿼드압축 후 세기 (0) | 2020.10.13 |