본문 바로가기
백준 알고리즘/BFS

백준 1967번 C++

by paysmile 2019. 8. 19.

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
const int MAX = 10001;
vector<pair<int,int>> tree[MAX];
int n;
int visited[MAX];

pair<int,int> bfs(int i) {
	pair<int,int> answer;
	queue<pair<int, int>> q;
	q.push(make_pair(i, 0));

	answer = make_pair(0, -1);
	while (!q.empty()) {
		int current = q.front().first;
		int value = q.front().second;
		q.pop();

		if (answer.second < value)
			answer = make_pair(current, value);
		for (int k = 0; k < tree[current].size(); k++) {
			int movei = tree[current][k].first;
			int movevalue = value + tree[current][k].second;

			if (visited[movei] == -1) {
				visited[movei] = 1;
				q.push(make_pair(movei, movevalue));
			}

		}
	}
	return answer;
}

int main(void) {
	pair<int, int> answer;
	cin >> n;
	for (int i = 0; i < n-1; i++) {
		int start, end, value;
		
		cin >> start >> end >> value;
		tree[start].push_back(make_pair(end, value));
		tree[end].push_back(make_pair(start, value));
	}
	memset(visited, -1, sizeof(visited));
	answer = bfs(1);
	memset(visited, -1, sizeof(visited));
	cout << bfs(answer.first).second << endl;
	return 0;
}

'백준 알고리즘 > BFS' 카테고리의 다른 글

백준 2251번 C++  (0) 2019.08.20
백준 1325번 C++  (0) 2019.08.20
백준 9019번 C++  (0) 2019.08.18
백준 2146번 C++  (0) 2019.08.17
백준 1963번 C++  (0) 2019.08.16