문제
https://www.acmicpc.net/problem/11724
11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주
www.acmicpc.net
소스코드
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include<memory.h>
using namespace std;
int n, m;
vector<int> g[1001];
bool check[1001];
queue<int> qu;
void bfs(int index) {
check[index] = true;
qu.push(index);
while (!qu.empty()) {
int node = qu.front();
qu.pop();
for (int i = 0; i < g[node].size(); i++) {
int next = g[node][i];
if (check[next]) continue;
check[next] = true;
qu.push(next);
}
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (!check[i]) {
bfs(i);
ans++;
}
}
cout << ans;
}
해설
연결요소란 한 정점이 이루는 그림이라 생각하면된다.
하나의 정점을 방문했을때 그릴 수 있는 그래프의 개수라고 생각하면된다.
https://github.com/kitten-master/algorithm/blob/master/graph/11724.cpp
GitHub - kitten-master/algorithm
Contribute to kitten-master/algorithm development by creating an account on GitHub.
github.com
dfs와 bfs를 구현해둔 소스입니다.
두개 참조하여 형태의 틀을 익히도록 하십시오.
'Algorithm > graph' 카테고리의 다른 글
[백준] 알고리즘 2667번 - 단지번호붙이기문제 (0) | 2021.08.18 |
---|---|
[백준] 알고리즘 1707번 - 이분 그래프문제 (0) | 2021.08.18 |
[백준] 알고리즘 1260번 - DFS와 BFS문제 (0) | 2021.08.17 |
[백준] 알고리즘 13023번 - ABCDE 문제 (0) | 2021.08.16 |
[백준] 알고리즘 2146번 - 다리 만들기 문제 (0) | 2021.02.04 |