오랜만에 풀어본 BFS문제이다.
양방향 그래프문제이고, 결과 벡터를 정렬한 후, 뒤에서부터 순회하여 계산 시간을 줄이려 했지만 그 전에 반복과정이 많아서 그런지 효과는 별로 없었다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
vector<vector<int>> barn;
void input_barn()
{
int N, M, A, B;
int i;
cin >> N >> M;
barn.resize(N + 1, vector<int>());
for (i = 0; i < M; i++)
{
cin >> A >> B;
barn[A].push_back(B);
barn[B].push_back(A);
}
return;
}
bool compare(pair<int, int> A, pair<int, int> B)
{
if (A.second == B.second)
{
return A.first > B.first;
}
else
{
return A.second < B.second;
}
}
void BFS()
{
queue <int> q;
vector<pair<int, int>> destination;
vector<bool> visited(barn.size() + 1, false);
int current, next, i, j, current_cnt = 0, q_size;
int answer, answer_distance, same_distance = 1;
q.push(1);
destination.push_back({ 1, 0 });
visited[1] = true;
while (!q.empty())
{
q_size = q.size();
for (j = 0; j < q_size; j++)
{
current = q.front();
q.pop();
for (i = 0; i < barn[current].size(); i++)
{
next = barn[current][i];
if (visited[next] == false)
{
q.push(next);
visited[next] = true;
destination.push_back({ next, current_cnt + 1 });
}
}
}
current_cnt++;
}
sort(destination.begin(), destination.end(), compare);
/*for (pair<int, int> temp : destination)
{
cout << temp.first << " " << temp.second << "\n";
}*/
answer = destination.back().first;
answer_distance = destination.back().second;
for (i = destination.size() - 2; i >= 0; i--)
{
if (destination[i].second == destination[i + 1].second)
{
same_distance++;
}
else
{
break;
}
}
cout << answer << " " << answer_distance << " " << same_distance << "\n";
return;
}
void find_answer()
{
BFS();
return;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
input_barn();
find_answer();
return 0;
}