티스토리 뷰

알고리즘/백준

백준 4195 (친구 네트워크) - java

김다미김태리신시아 2023. 10. 5. 16:39

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

 

4195번: 친구 네트워크

첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스의 첫째 줄에는 친구 관계의 수 F가 주어지며, 이 값은 100,000을 넘지 않는다. 다음 F개의 줄에는 친구 관계가 생긴 순서대로 주어진

www.acmicpc.net

문제

민혁이는 소셜 네트워크 사이트에서 친구를 만드는 것을 좋아하는 친구이다. 우표를 모으는 취미가 있듯이, 민혁이는 소셜 네트워크 사이트에서 친구를 모으는 것이 취미이다.

어떤 사이트의 친구 관계가 생긴 순서대로 주어졌을 때, 두 사람의 친구 네트워크에 몇 명이 있는지 구하는 프로그램을 작성하시오.

친구 네트워크란 친구 관계만으로 이동할 수 있는 사이를 말한다.

 

유형 : 분리 집합(union - find) + 분리 집합에서 count

 

접근

  • 친구의 이름이 문자열로 주어진다. 분리 집합의 노드 번호를 숫자로 사용하기 위해서 단순하게 HashMap<String,Integer>를 사용했다.
  • 분리집합에서 원소의 개수를 세는 방법은 무엇일까 ? (해당 집합에 속하는 원소의 개수)
    • 단순하게 count[] 라는 배열을 만들고 부모가 갱신될 때마다 count[parent]에 count[child]만큼 더하면 된다.

분리 집합에 원소 개수 추가

    static void union(int x,int y){
        x = find(x);
        y = find(y);

        if(x == y)
        {
            return;
        }

        else if( x < y) {
            root[y] = x;
            count[x] += count[y];
        }
        else {
            root[x] = y;
            count[y] += count[x];
        }
    }

전체 코드

import java.io.*;
import java.util.*;

public class Main {
    static int k = 0;
    static int n = 0;

    static HashMap<String,Integer> map;
    static int[] root;
    static int[] count;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        k = Integer.parseInt(br.readLine());

        StringBuilder sb = new StringBuilder();

        for(int m = 1; m <= k; m++){
            n = Integer.parseInt(br.readLine());
            root = new int[2*(n+1)];
            count = new int[2*(n+1)];

            for(int i =1 ;i<=2*n+1;i++){
                root[i] = i;
                count[i] = 1;
            }
            int start = 1;
            map = new HashMap<>();

            for(int i=1;i<=n;i++){
                StringTokenizer st = new StringTokenizer(br.readLine()," ");
                String x = st.nextToken();
                String y = st.nextToken();

                if(!map.containsKey(x)){
                    map.put(x,start);
                    start = start + 1;
                }

                if(!map.containsKey(y)){
                    map.put(y,start);
                    start = start + 1;
                }

                int nx = map.get(x);
                int ny = map.get(y);

                union(nx,ny);
                sb.append(count[Math.min(find(nx),find(ny))]+"\n");
            }
        }
        System.out.print(sb);
        br.close();
    }

    static int find(int x){
        if(root[x] == x)
            return root[x];

        return root[x] = find(root[x]);
    }

    static void union(int x,int y){
        x = find(x);
        y = find(y);

        if(x == y)
        {
            return;
        }

        else if( x < y) {
            root[y] = x;
            count[x] += count[y];
        }
        else {
            root[x] = y;
            count[y] += count[x];
        }
    }
}

'알고리즘 > 백준' 카테고리의 다른 글

백준 13904 (과제) - java  (1) 2023.10.09
백준 15644 (구슬 탈출 3) - java  (1) 2023.10.08
백준 17299 (오등큰수) - java  (0) 2023.10.04
백준 17472 (다리 만들기 2) - java  (0) 2023.10.04
백준 12851 (숨바꼭질 2) - java  (1) 2023.10.03