알고리즘 문제/Programmers
가장 먼 노드
parkit
2019. 5. 11. 09:51
728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/49189
BFS를 통해 거리를 dist에 저장한다.
dist[i] = 1번 노드에서 i번 노드로 가는 최단 경로의 길이(간선의 개수)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | #include <iostream> #include <deque> #include <list> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> #include <set> #pragma warning(disable:4996) #pragma comment(linker, "/STACK:336777216") using namespace std; int dist[20002] = { 0, }, Max = 0; vector<int> v[20002]; int BFS(int e) { int ret = 0; queue<int> q; q.push(1); dist[1] = 0; while (!q.empty()) { int qSize = q.size(); while (qSize--) { int now = q.front(); q.pop(); for (auto i : v[now]) if (dist[i] == -1) { dist[i] = dist[now] + 1; Max = max(Max, dist[i]); q.push(i); } } } for (int i = 1; i <= e; i++) if (dist[i] == Max) ++ret; return ret; } int solution(int n, vector<vector<int>> edge) { memset(dist, -1, sizeof(dist)); for (int i = 0; i < edge.size(); i++) { int from = edge[i].at(0), to = edge[i].at(1); v[from].push_back(to); v[to].push_back(from); } return BFS(n); } int main(void) { vector<vector<int> > v = { {3, 6}, {4, 3}, {3, 2}, {1, 3}, {1, 2}, {2, 4}, {5, 2} }; cout << "답 = " << solution(6, v) << '\n'; return 0; } | cs |
728x90
반응형