백준 18352 특정 거리의 도시 찾기

치즈·2022년 11월 30일

BOJ

목록 보기
24/45
#include <iostream>
#include <vector>
#include <queue>
#define MAX 300001
#define INF 1e9
using namespace std;

int N, M, K, X;
vector<pair<int,int>> graph[MAX];
priority_queue<pair<int, int>> pq;
vector<int> dist;

void input(){
  cin >> N >> M >> K >> X;
  dist.resize(N+1, INF);
  for(int i = 0; i < M; i++){
    int a, b;
    cin >> a >> b;
    graph[a].push_back({b, 1});
  }
}

void solve(){
  pq.push({0, X});
  dist[X] = 0; //출발 도시 -> 출발 도시 항상 0
  while(!pq.empty()){
    int cost = -pq.top().first;
    int node = pq.top().second;
    pq.pop();

    if(dist[node] < cost) continue;
    for(int i = 0; i < graph[node].size(); i++){
      int nextCost = graph[node][i].second;
      int nextNode = graph[node][i].first;

      if(dist[nextNode] > cost + nextCost){
        dist[nextNode] = cost + nextCost;
        pq.push({-dist[nextNode], nextNode});
      }
    }
  }
}

void print_(){
  bool flag = false;
  for(int i = 1; i <= N; i++){
    if(dist[i] == K){
      flag = true;
      cout << i << "\n";
    }
  }
  if(flag == false) cout << "-1\n";
}

int main(void){
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  input();
  solve();
  print_();
  return 0;
}

보편적인 다익스트라 문제인 듯.
프린트 할 때에만, dist값과 비교해서 K값과 동일한 것이 있는 경우에 프린트, 그렇지 않다면 flag로 판단해서 -1 출력하도록 한다.

profile
차근차근 배워나가요

0개의 댓글