출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 5567 결혼식(bfs)

알고리즘

by 장동균 2020. 8. 26. 22:02

본문

acmicpc.net/problem/5567

 

5567번: 결혼식

문제 상근이는 자신의 결혼식에 학교 동기 중 자신의 친구와 친구의 친구를 초대하기로 했다. 상근이의 동기는 모두 N명이고, 이 학생들의 학번은 모두 1부터 N까지이다. 상근이의 학번은 1이다.

www.acmicpc.net

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int MAX = 500 + 1;
int n, m;
vector<int> graph[MAX];
bool visited[MAX];
queue<int> q;
int cnt;

void bfs()
{
    visited[1] = true;
    for (int i = 0; i < graph[1].size(); i++)
    {
        q.push(graph[1][i]);
        visited[graph[1][i]] = true;
    }
    while (!q.empty())
    {
        int nextNode = q.front();
        q.pop();
        for (int i = 0; i < graph[nextNode].size(); i++)
        {
            if (!visited[graph[nextNode][i]])
            {
                visited[graph[nextNode][i]] = true;
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int from, to;
        cin >> from >> to;
        graph[from].push_back(to);
        graph[to].push_back(from); //굳이 이 부분이 들어가야 할까에 대해 생각해보자.
    }
    bfs();
    for (int i = 2; i <= n; i++)
    {
        if (visited[i])
        {
            cnt += 1;
        }
    }
    cout << cnt;
}

크게 어렵지 않음 문제.

 

to->push 부분도 넣어야 하나 생각하다가 생각해보니 당연히 넣어야 했다. 애초에 제시된 edge들은 무방향인데 내가 임의로 방향을 만들어 버린다면 입력값들의 위치가 반대로 됐을 때 큰일난다.

'알고리즘' 카테고리의 다른 글

백준 1926 그림(dfs)  (0) 2021.01.14
백준 2636 치즈(bfs)  (0) 2020.08.26
백준 1963 소수 경로(에스테라노스의 체, bfs)  (0) 2020.08.19
백준 3055 탈출(bfs)  (0) 2020.08.14
백준 14891 톱니바퀴(구현, 시뮬레이션)  (0) 2020.08.13

관련글 더보기

댓글 영역