문제 - https://www.acmicpc.net/problem/3830

 

3830번: 교수님은 기다리지 않는다

교수님의 질문 (? a b)이 입력으로 들어올 때 마다, 지금까지 측정한 결과를 바탕으로 a와 b의 무게 차이를 계산할 수 있다면, b가 a보다 얼마나 무거운지를 출력한다. 무게의 차이의 절댓값이 1,000,

www.acmicpc.net

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

public class Main {

    static int N, M;
    static int[] parent, weight;

    public static void main(String[] args) throws Exception {
//        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./input.txt")));
        StringTokenizer st;

        do{
            st = new StringTokenizer(br.readLine());
            N = Integer.parseInt(st.nextToken());
            M = Integer.parseInt(st.nextToken());

            parent = new int[N+1];
            weight = new int[N+1];
            for (int i = 1; i <= N; i++)
                parent[i] = i;

            int a, b, w;
            for (int i = 0; i < M; i++) {
                st = new StringTokenizer(br.readLine());
                String t = st.nextToken();
                a = Integer.parseInt(st.nextToken());
                b = Integer.parseInt(st.nextToken());
                if (t.equals("!")){
                    w = Integer.parseInt(st.nextToken());
                    union(a, b, w);
                } else{
                    if(find(a)==find(b))
                        bw.write(weight[b]-weight[a]+"\n");
                    else
                        bw.write("UNKNOWN\n");
                }
            }
        } while(N!=0 && M!=0);

        bw.flush();
        bw.close();
        br.close();
    }
    public static void union(int a, int b, int w){
        int pa = find(a);
        int pb = find(b);
        if (pa!=pb){
            weight[pb] = weight[a] - weight[b] + w;
            parent[pb] = pa;
        }
    }
    public static int find(int id){
        if (parent[id]==id)
            return id;
        int pid = find(parent[id]);
        weight[id] += weight[parent[id]];
        return parent[id] = pid;
    }
}

 

union & find를 이용한 대표적인 문제이다. union/find 구현을 조금 더 잘 이해할 필요가 있어보인다..

'공부 > algorithm' 카테고리의 다른 글

BOJ 단절점(11266) - Java  (0) 2021.08.09
BOJ 도로 네트워크(3176) - Java  (0) 2021.08.06
BOJ 게임 개발(1516) - Java  (0) 2021.08.04
BOJ 키 순서(2458) - Java  (0) 2021.08.04
BOJ LCA 2(11438) - Java  (0) 2021.08.04

+ Recent posts