알고리즘&자료구조/문제

[BOJ] 2606 바이러스 C++

Nakuri 2023. 2. 2. 06:44
728x90

개요

https://www.acmicpc.net/problem/2606

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net

실버 3급 그래프 탐색 문제다.

본문

풀이

그래프 탐색 문제 중 저 난이도 문제인듯하다.

제한이 크게 없어 BFS, DFS 중 어느 것을 사용해도 문제가 없을 것이라 판단했다.

queue를 활용한 인접 리스트(vector) 기반 BFS로 풀었다.

1번 컴퓨터는 제외이기 때문에 이 점에 유의해야 한다.

코드

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
constexpr int RANGE = 102;

int bfs(vector<int>* g, int start) {
	int visited[RANGE]{};
	int cnt = 0;
	queue<int> q;
	q.push(start);

	while (!q.empty())
	{
		int nowV = q.front();
		q.pop();

		if (visited[nowV]) continue;
		visited[nowV] = true;
		cnt++;

		for (int i = 0; i < g[nowV].size(); i++)
			q.push(g[nowV][i]);
	}
	return cnt-1;
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	int v, e;
	vector<int> graph[RANGE]{};

	cin >> v >> e;

	for (int i = 1; i <= e; i++) {
		int from, to;
		cin >> from >> to;
		graph[from].push_back(to);
		graph[to].push_back(from);
	}

	int cnt = bfs(graph, 1);
	cout << cnt;
}

 

'알고리즘&자료구조 > 문제' 카테고리의 다른 글

[BOJ] 2178 미로탐색 C++  (0) 2023.02.03
[BOJ] 2644 촌수계산 C++  (0) 2023.02.03
[BOJ] 2309 일곱 난쟁이 C++  (0) 2023.02.02
[BOJ] 1260 DFS와 BFS C++  (0) 2023.02.02
[BOJ] 2579 계단오르기 C++  (0) 2023.01.19