오늘의 알고리즘
[C++] 백준 1967 트리의 지름
하늘하늘 .
2022. 10. 10. 21:49
#include <iostream>
#include <vector>
#include <stack>
#include <string.h>
std::vector<std::pair<int, int>> vec[10001] = {};
bool visit[10001] = {};
int iMax = 0;
int iEnd = 0;
void DFS(int iStart)
{
std::stack<std::pair<int, int>> stk = {};
stk.push({ iStart, 0 });
visit[iStart] = true;
while (!stk.empty())
{
int iNow = stk.top().first;
int iCost = stk.top().second;
stk.pop();
if (iCost > iMax)
{
iMax = iCost;
iEnd = iNow;
}
for (int i = 0; i < vec[iNow].size(); ++i)
{
int iNext = vec[iNow][i].first;
int iNextCost = vec[iNow][i].second;
if (!visit[iNext])
{
visit[iNext] = true;
stk.push({ iNext, iCost + iNextCost});
}
}
}
}
int main()
{
int N = 0;
std::cin >> N;
for (int i = 0; i < N - 1; ++i)
{
int iFirst = 0;
int iSecond = 0;
int iThird = 0;
std::cin >> iFirst >> iSecond >> iThird;
vec[iFirst].push_back({iSecond, iThird});
vec[iSecond].push_back({iFirst, iThird});
}
DFS(1);
memset(visit, false, sizeof(visit));
DFS(iEnd);
std::cout << iMax;
return 0;
}
처음엔 BFS로 전체검색을 이용해서 풀려고 했습니다.
아무리 생각해도 아닌 것 같아 DFS로 풀었습니다.
지름이기 때문에 어느 점에서 가장 끝 점인지 확인했고,
그 점에서 가장 긴 길이가 지름일 것이라고 생각하고 푼 문제입니다.