본문 바로가기
algorithm

[백준/c++][11724] 연결 요소의 개수

by blogsy 2019. 10. 10.

문제

 

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

 

입력

 

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.

 

출력

 

첫째 줄에 연결 요소의 개수를 출력한다.

 

코드

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

vector<int> a[1001];
bool check[1001];
int cnt = 0;

void dfs(int node) {
	check[node] = true;
	for (int i = 0; i < a[node].size(); i++) {
		int next = a[node][i];
		if (check[next] == false) {
			dfs(next);
		}
	}
}

int main()
{
	int n, m;
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		int u, v;
		cin >> u >> v;
		a[u].push_back(v);
		a[v].push_back(u);
	}

	for (int i = 1; i <= n; i++) {
		if (check[i] == false) {
			dfs(i);
			cnt++;
		}
	}

	cout << cnt;

	return 0;
}

 

 

메모

 

'algorithm' 카테고리의 다른 글

[백준/c++][2667]단지번호붙이기  (0) 2019.10.11
[백준/c++][1707]이분 그래프  (0) 2019.10.11
[백준/c++][1182] 부분수열의 합  (0) 2019.10.04
[백준/c++][11723] 집합  (0) 2019.10.04
[백준/c++][14501] 퇴사  (0) 2019.10.03

댓글