티스토리 뷰

알고리즘/백준

백준 2617 (구슬 찾기) - java

김다미김태리신시아 2023. 6. 21. 22:18

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

 

2617번: 구슬 찾기

모양은 같으나, 무게가 모두 다른 N개의 구슬이 있다. N은 홀수이며, 구슬에는 번호가 1,2,...,N으로 붙어 있다. 이 구슬 중에서 무게가 전체의 중간인 (무게 순서로 (N+1)/2번째) 구슬을 찾기 위해서

www.acmicpc.net

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

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

    static boolean[] visit;

    static int result = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());

        boolean[][] big_a = new boolean[n+1][n+1]; // [a][b] -> a < b
        boolean[][] small_a = new boolean[n+1][n+1]; // [a][b] -> a > b
 
        for(int i=1;i<=m;i++)
        {
            st = new StringTokenizer(br.readLine(), " ");

            int big = Integer.parseInt(st.nextToken());
            int small = Integer.parseInt(st.nextToken());

            big_a[small][big] = true;
            small_a[big][small] = true;
        }

        int count = 0;
        for(int i=1; i<= n; i++) {
            visit = new boolean[n + 1]; // 방문 배열 초기화
            visit[i] = true; // 시작점 방문 체크
            result = 0; // 개수 측정
            search(i,big_a); // 큰 거의 개수 탐색
            int tmp1 = result;

            visit = new boolean[n + 1];
            visit[i] = true;
            result = 0;
            search(i,small_a);

            int tmp2 = result;

            if(tmp1 > (n/2) || tmp2 > (n/2))
            {
                count = count + 1;
            }
        }

        System.out.println(count);
        br.close();
    }

    static void search(int start,boolean[][] big_a)
    {
        for(int i=1;i<=n;i++)
        {
            if(big_a[start][i])
            {
                if(!visit[i])
                {
                    visit[i] = true;
                    result = result + 1; // 개수 한개 증가
                    search(i,big_a);
                }
            }
        }
    }

}