백준
백준 소스코드 [C++] 11724 연결 요소의 개수
Hani_Levenshtein
2020. 11. 16. 13:08
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
백준 소스코드 [C++] 11724 연결 요소의 개수
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
typedef long long ll;
using namespace std;
#define all(v) v.begin(),v.end()
int n,sum=0;
bool checked[1001];
vector <int> arr[1001];
void bfs() {
queue <int> q;
for (int i = 1;i <= n;i++) {
if (checked[i] == false) {
checked[i] = true;
sum++;
q.push(i);
}
while (q.empty() != true) {
int t=q.front();
q.pop();
for (auto x:arr[t]) {
if (checked[x] == false) {
checked[x] = true;
q.push(x);
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int m,u,v;
cin >> n >> m;
for (int i = 0;i < m;i++) {
cin >> u >> v;
arr[u].push_back(v);
arr[v].push_back(u);
}
bfs();
cout << sum;
return 0;
}