본문 바로가기
알고리즘 문제풀이/백준

[백준 6118] 숨바꼭질

by m2162003 2021. 1. 1.

www.acmicpc.net/problem/6118

 

6118번: 숨바꼭질

재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재서기는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자.   재

www.acmicpc.net

레벨별 순회 후 리프노드 중 가장 적은 번호의 노드를 리턴한다.

bfs를 사용. 

#include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;
int n, m;

vector<int> v[20001];
int visited[20001];
queue<int> q;
int main(void)
{
  scanf("%d%d", &n, &m);

  for (int i = 0; i < m; i++)
  {
    int a, b;
    scanf("%d%d", &a, &b);
    v[a].push_back(b);
    v[b].push_back(a);
  }

  q.push(1);
  visited[1] = 1;
  vector<int> ans;
  while (!q.empty())
  {
    int cur = q.front();
    q.pop();

    for (auto a : v[cur])
    {
      if (visited[a] == 0)
      {
        q.push(a);
        visited[a] = visited[cur] + 1;
      }
    }
  }
  int max = 0, cnt = 0, res = 0;
  for (int i = 2; i <= n; i++)
  {
    if (visited[i] > max)
    {
      res = i;
      max = visited[i];
      cnt = 1;
    }
    else if (visited[i] == max)
    {
      cnt++;
    }
  }

  printf("%d %d %d\n", res, visited[res] - 1, cnt);
  return 0;
}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 14588] Line Friends (Small)  (0) 2021.01.02
[백준 2015] 수들의 합 4  (0) 2021.01.01
[백준 2262] 토너먼트 만들기  (0) 2020.12.31
[백준 20310] 타노스  (0) 2020.12.31
[백준 17392] 우울한 방학  (0) 2020.12.31

댓글