๋ฐฑ์ค€/C++

[๋ฐฑ์ค€/C++] 18352 ํŠน์ •๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ

yulee_to 2022. 7. 16. 21:10

๋ฐฑ์ค€


๐Ÿค”๋ฌธ์ œ ์ดํ•ด

์ตœ๋‹จ๊ฑฐ๋ฆฌ๋กœ ๋„๋‹ฌํ•  ์ˆ˜ ์žˆ๋Š” ๋„์‹œ๋“ค ์ค‘ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๊ฐ€ k์ธ ๊ฒฝ์šฐ๋งŒ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ๋ฌธ์ œ์ด๋‹ค.


๐Ÿ’ก์ฒซ๋ฒˆ์งธ ์•„์ด๋””์–ด

๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ์ธ๋ฐ ๊ทธ๋ƒฅ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์ˆ˜ํ–‰ํ•œ ํ›„ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k์ธ ๊ฐ’๋งŒ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

 

๐Ÿ”ฅํ’€์ด๐Ÿ”ฅ

๋‹ค์ต์ŠคํŠธ๋ผ ์ˆ˜ํ–‰ ํ›„ dist[i]๊ฐ’์ด k์ธ i๋งŒ ์ถœ๋ ฅ

 

โŒํŠธ๋Ÿฌ๋ธ” ์ŠˆํŒ…

dist๋ฅผ ๋ชจ๋‘ INF๋ฅผ ๋ฐ”๊ฟ”์ฃผ๊ณ  ์‹œ์ž‘์ ์ธ x๋งŒ 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ์ฝ”๋“œ๊ฐ€ ์—†์–ด์„œ ์ฒซ ์ œ์ถœ์—์„œ ํ‹€๋ ธ๋‹ค.

dist[x] =0 ์ฝ”๋“œ ์ถ”๊ฐ€ ํ›„ ์ œ๋Œ€๋กœ ๋Œ์•„๊ฐ”๋‹ค.


#include <iostream>
#include <queue>
#include <vector>

using namespace std;
#define INF 987654321

int n, m, k, x;
vector<vector<int>> edge;
int dist[300002];

int main() {
    cin.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> n >> m >> k >> x;
    edge.resize(n + 1);
    int a, b;

    for (int i = 0; i < m; i++) {
        cin >> a >> b;
        edge[a].push_back(b);
    }

    for (int i = 1; i <= n; i++) {
        dist[i] = INF;
    }
    dist[x] = 0; //ํ•ด๋‹น ์ฝ”๋“œ ๋ˆ„๋ฝ์œผ๋กœ 86%์—์„œ ํ‹€๋ฆผ

    priority_queue<pair<int, int>> pq;
    pq.push({0, x});

    while (!pq.empty()) {
        int cost = -pq.top().first;
        int now = pq.top().second;
        pq.pop();
        if (dist[now] < cost) continue;

        for (auto u: edge[now]) {
            int next_cost = cost + 1;

            if (dist[u] <= next_cost) continue;
            dist[u] = next_cost;
            pq.push({-(next_cost), u});
        }
    }
    int flag = 0;
    for (int i = 1; i <= n; i++) {
        if (dist[i] == k) {
            cout << i << "\n";
            flag = 1;
        }
    }
    if (flag == 0) cout << -1;

}

 

๐Ÿ”—์ฐธ๊ณ ํ•  ๋ฌธ์ œ

 

 

[๋ฐฑ์ค€/C++] 1753๋ฒˆ ์ตœ๋‹จ๊ฒฝ๋กœ

๐Ÿค”๋ฌธ์ œ ์ดํ•ด ์‹œ์ž‘์ ์—์„œ ๊ฐ ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ตœ์†Œ ๋น„์šฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๐Ÿ’ก์ฒซ๋ฒˆ์งธ ์•„์ด๋””์–ด ๋ฌธ์ œ๊ฐ€ ๊ทธ๋ƒฅ ๋”ฑ ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ๋ผ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์ด์šฉํ–ˆ๋‹ค. ๐Ÿ”ฅํ’€์ด๐Ÿ”ฅ ๋‹ค์ต์ŠคํŠธ๋ผ

yulee.tistory.com

 

728x90