반응형
    
    
    
  250x250
    
    
  
                              Notice
                              
                          
                        
                          
                          
                            Recent Posts
                            
                        
                          
                          
                            Recent Comments
                            
                        
                          
                          
                            Link
                            
                        
                    | 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 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 | 
                            Tags
                            
                        
                          
                          - 카이스트맛집
- glfw
- html
- 프로그래머스
- 우선순위큐
- 리사이클러뷰
- 분리집합
- 자바스크립트
- 몰입캠프후기
- 대전맛집
- 프래그먼트
- node.js
- 어은동맛집
- 궁동
- DP
- 카이스트
- nodeJS
- 앱개발
- 타입스크립트
- 안드로이드스튜디오
- 몰입캠프
- computergraphics
- MySQL
- 알고리즘
- 백준
- BFS
- 자바
- 컴퓨터그래픽스
- 위상정렬
- 후기
                            Archives
                            
                        
                          
                          - Today
- Total
소근소근
[프로그래머스 - 네트워크] BFS, 분리집합(disjoint set) Union & Find C++ 본문
728x90
    
    
  반응형
    
    
    
  SMALL
    BFS/DFS 분류에 있는 문제였지만, 분리집합으로 풀었다.
컴퓨터 두대가 연결 되면 같은 네트워크(같은 집합)으로 분류되기 때문이다.
연결된 컴퓨터 두대는 union해서 같은 집합으로 보고, 마지막에 집합의 개수를 출력하면 된다.
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int parent[200];
map <int,int> m;
int Find(int x){
    if(x==parent[x]) return x;
    return parent[x] = Find(parent[x]);
}
void Union(int x, int y){
    int px = Find(x);
    int py = Find(y);
    if(px != py){
        parent[px] = py;
    }
}
int solution(int n, vector<vector<int>> comps) {
    int answer = 0;
    for(int i=0;i<n;i++){
        parent[i]=i;
    }
    for(int i=0;i<n;i++){
        for(int j= i+1 ; j<n ; j++){
            if(comps[i][j] == 1){
                Union(i,j);
            }
        }
    }
    for(int i=0;i<n;i++){
        int n = Find(i);
        if(m.find(n) == m.end()){
            //m[n]++;
            answer++;
        }
        else{
            m[n] =1;
        }
    }
    return answer;
}
728x90
    
    
  반응형
    
    
    
  LIST
    'Algorithm' 카테고리의 다른 글
| [백준 BOJ 1937 glod3 - 욕심쟁이 판다] DFS(?) , DP C++ (0) | 2022.01.12 | 
|---|---|
| [프로그래머스 - 단어 변환] BFS C++ (0) | 2022.01.09 | 
| [프로그래머스 - 타겟 넘버] BFS C++ (0) | 2022.01.08 | 
| [프로그래머스 - 베스트앨범] 해시 C++ (0) | 2022.01.06 | 
| [백준 BOJ 4195 glod2 - 친구 네트워크] 해시, 분리집합(disjoint set / union find) C++ (0) | 2022.01.05 |