반응형
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 | #include <iostream> #include <queue> #include <vector> #include <cstring> using namespace std; int n, u, v, w; struct Edge { int to; int cost; Edge(int to, int cost) : to(to), cost(cost) { } }; vector<Edge> a[10001]; int c[10001]; int d[10001]; void bfs(int start) { memset(d, 0, sizeof(d)); memset(c, 0, sizeof(c)); queue<int> q; c[start] = 1; q.push(start); while (!q.empty()) { int x = q.front(); q.pop(); for (int i = 0; i<a[x].size(); i++) { Edge &e = a[x][i]; if (c[e.to] == 0) { d[e.to] = d[x] + e.cost; q.push(e.to); c[e.to] = 1; } } } } int main() { cin >> n; for (int i = 0; i < n-1; i++) { cin >> u >> v >> w; a[u].push_back(Edge(v, w)); a[v].push_back(Edge(u, w)); } bfs(1); int start = 1; for (int i = 2; i <= n; i++) { if (d[i] > d[start]) { start = i; } } bfs(start); int ans = d[1]; for (int i = 2; i <= n; i++) { if (ans < d[i]) { ans = d[i]; } } cout << ans; } | cs |
'Algorithm' 카테고리의 다른 글
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 11403번:경로 찾기(DFS) 답 (0) | 2017.02.15 |
---|---|
(C++) - 백준(BOJ) 11723 : 집합 (0) | 2017.02.14 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 10026번:적록색약 답 (0) | 2017.02.11 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 1850번:최대공약수 답 (0) | 2017.02.10 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 3036번:링 답 (0) | 2017.02.10 |