๐ค๋ฌธ์ ์ดํด
์ต๋จ๊ฑฐ๋ฆฌ๋ก ๋๋ฌํ ์ ์๋ ๋์๋ค ์ค ์ต๋จ๊ฑฐ๋ฆฌ๊ฐ 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;
}
๐์ฐธ๊ณ ํ ๋ฌธ์
728x90
'๋ฐฑ์ค > C++' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค/C++] 14716๋ฒ ํ์๋ง (0) | 2022.07.16 |
---|---|
[๋ฐฑ์ค/C++] 1149๋ฒ RGB๊ฑฐ๋ฆฌ (0) | 2022.07.16 |
[๋ฐฑ์ค/C++] 2234๋ฒ ์ฑ๊ณฝ (0) | 2022.07.16 |
[๋ฐฑ์ค/C++] 2252๋ฒ ์ค ์ธ์ฐ๊ธฐ (0) | 2022.07.16 |
[๋ฐฑ์ค/C++] 2056๋ฒ ์์ (0) | 2022.07.16 |