개발자 톡

연습문제 톡 우물 안 개구리

2,3,19 테케 런타임에러 원인 좀 알려주세요..

등록일
2024-06-22 15:16:32
조회수
156
작성자
xogh0175

```java

import java.io.*;

import java.util.*;


public class Main {

  static int[] root;

  static long[] w;

  public static void main(String[] args) throws IOException {

    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

    StringTokenizer st = new StringTokenizer(bf.readLine());


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

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


    w = new long[n+1];

    // 루트 노드 만들기

    root = make(n);


    st = new StringTokenizer(bf.readLine());


    // 무게 입력.

    for(int i=1;i<=n;i++){

      w[i] = Long.parseLong(st.nextToken());

    }


    for(int i=0;i<m;i++){

      st = new StringTokenizer(bf.readLine());

      int a = Integer.parseInt(st.nextToken());

      int b = Integer.parseInt(st.nextToken());

      union(a,b);

    }


    int cnt=0;

    for(int node=1; node<root.length; node++){

      if(root[node]==node){

        cnt++;

      }

    }

    System.out.println(cnt);

//

//    System.out.println("root = " + Arrays.toString(root));

//    System.out.println("w = " + Arrays.toString(w));



  }


  private static int[] make(int n){

    int[] root = new int[n+1];

    for(int i=1;i<=n;i++){

      root[i] = i;

    }

    return root;

  }


  private static int find(int node){

    if(node == root[node]){

      return node;

    }

    return root[node] = find(root[node]);

  }


  private static void union(int a, int b){

    int rootA = find(a);

    int rootB = find(b);


    if(rootA==rootB) return; // root가 같으면 생략한다.


    // 무게가 더 높은 사람으로 부모노드를 변경한다.

    if(w[a]==w[b]){ // A == B => 두 노드를 서로 맞바꾼다.

      root[a] = rootB;

      root[b] = rootA;

    }else if(w[a] > w[b]){ // A가 더 높은 무게면 B의 부모노드를 A의 부모노드로 변경한다.

      root[b] = rootA;

    }else if(w[a] < w[b]){ // A의 부모 노드를 B의 부모 노드로 변경한다.

      root[a] = rootB;

    }


  }


}


```


#우물_안_개구리
#java
#런타임에러

이 카테고리의 톡 더보기