반응형

문제 출처

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


dfs, bfs고민하다 bfs로 푼 문제

1번 컴퓨터와 연결된 모든 컴퓨터의 갯수를 출력하는 문제이다.

dfs보다 bfs가 더 빠를 것이라 예상 되었다.

기본적으로 bfs 또는 dfs를 연습할 수 있는 문제

점점 문제를 풀수록 문제 이해를 하면 dfs bfs구현자체가 정형화 되있기 때문에 익숙해 지는 기분이다.

아직 많이 부족하다는 반증일수도....


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 101
using namespace std;
int com;
int couple;
bool network[MAX][MAX];
bool visit[MAX];
queue<int> q;
int cnt=0;
 
void init() {
    scanf("%d"&com);
    scanf("%d"&couple);
    
    for(int i=1; i<=couple; i++) {
        int s, e;    //start end
        scanf("%d %d"&s, &e);
        network[s][e]=true;
        network[e][s]=true;
    }
}
 
void bfs(int s) {
    q.push(s);
    visit[s]=true;
 
    while(!q.empty()) {
        int s = q.front();
        q.pop();
 
        for(int i=1; i<=com; i++) {
            if(network[s][i] && network[i][s] && !visit[i]) {
                visit[i]=1;
                q.push(i);
                cnt++;
            }
        }
    }
}
 
int main(void) {
    init();
    bfs(1);
    cout<<cnt;
    return 0;
}
cs




반응형

'Algorithm' 카테고리의 다른 글

[Programmers 43165] 타겟넘버  (0) 2018.12.31
[BOJ 2644] 촌수계산  (0) 2018.12.31
[BOJ 2583] 영역구하기  (0) 2018.12.28
[TopCoder 전체탐색] 회문(Palindrome)  (0) 2018.12.20
[TopCoder 전체탐색] 암호(Cryptography)  (0) 2018.12.20

+ Recent posts