풀이 과정
다익스트라 알고리즘의 기본 문제이다.
양방향으로 통행할 수 있다고 했으니 시작 -> 도착, 도착 -> 시작 둘 다 연결해준다.
#include <queue>
#include <vector>
using namespace std;
const int INF = 1e9;
vector<int> dist;
vector<pair<int, int>> edge[51];
priority_queue<pair<int, int>> pq; // 가중치, 정점
void dijkstra(int n){
dist.resize(n + 1, INF);
dist[1] = 0;
pq.push({0, 1});
while(!pq.empty()){
int cost = -pq.top().first;
int now = pq.top().second;
pq.pop();
if(dist[now] < cost) continue;
for(int i = 0; i < edge[now].size(); i++){
int next = edge[now][i].first;
int nextcost = edge[now][i].second;
if(dist[next] > dist[now] + nextcost){
dist[next] = dist[now] + nextcost;
pq.push({-dist[next], next});
}
}
}
}
int solution(int N, vector<vector<int>> road, int K) {
int answer = 0;
for(int i = 0; i < road.size(); i++){
edge[road[i][0]].push_back({road[i][1], road[i][2]}); // 도착 정점, 가중치
edge[road[i][1]].push_back({road[i][0], road[i][2]});
}
dijkstra(N);
for(int i = 1; i <= N; i++){
if(dist[i] <= K) answer++;
}
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level2] 영어 끝말잇기 c++ (0) | 2022.10.21 |
---|---|
[프로그래머스][Level2] 수식 최대화 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] [3차] n진수 게임 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 카펫 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 소수 찾기 c++ (0) | 2022.10.21 |