코딩테스트 준비하기/알고리즘 개념과 관련 문제

객체 비교 후 정렬 - 냉장고

코드 살인마 2020. 3. 9. 19:49
728x90

서론

일반적으로 정렬을 할 때 sort함수를 이용하여 정렬을 한다.

그러나 객체에 대해서 sort를 하려면 일반적인 sort함수로는 불가능하다.

객체를 sort 하려면 객체의 속성 중 하나를 기준으로 잡고 sort를 해야한다.

객체를 sort 하기 위해서는 compare함수의 Override이 필요하다.

구현 코드

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;


class Point implements Comparator<Point>{ //특정 속성을 기준으로 정렬하고 싶다!!
    int x;
    int y;

    public Point() {

    }

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int compare(Point o1, Point o2) {
        //return 1; // 리턴 음수 ---> 자리변경, 리턴 0 또는 양수 ----> 변화없음
        //return o1.y - o2.y; //y값 기준 오름차순
        //return o2.y - o1.y; //y값 기준 내림차순

//        문제) y값을 기준으로 내림차순 정렬하고 만약 y값이 같다면 x값으로 오름차순 정렬하시오.
        if(o2.y -o1.y < 0) return -1;
        else if(o2.y == o1.y) {
            return o1.x - o2.x;
        }
        return 1;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("x = ").append(x).append(" y = ").append(y);
        return builder.toString();
    }
}

문제에 적용

문제 :http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=1101&sca=3050

 

JUNGOL | 냉장고 > 문제은행

N개의 화학 물질 C1, C2, …, Cn이 있다.  이들 각각은 보관되어야 할 온도가 각기 다른데, 각 Ci마다 최저 보관 온도 xi와 최고 보관 온도 yi가 정해져 있다.  즉 Ci는 온도 xi이상, yi이하의 온도에서 보관되어야만 안전하다. 이 화학 물질들을 모두 보관하기 위해서는 여러 대의 냉장고가 필요한데 가능하면 적은 수의 냉장고를 사용하고 싶다.  이를 해결하는 프로그램을 작성하시오.

www.jungol.co.kr

알고리즘

1. 최고온도보다 최저온도가 크면 무조건 냉장고 1개가 필요하다.

2. 최고온도를 기준으로 오름차순 정렬한다.

3. 최고온도와 최저온도를 비교한다.

구현코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class 냉장고 {
    static int[][] tempa;
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer s;
        int N = Integer.parseInt(in.readLine().trim());
        tempa = new int[N][2];
        //최고 온도보다 최저온도가 크면 무조건 냉장고 1개 더 필요
        for (int i = 0; i < N; i++) {
            s = new StringTokenizer(in.readLine()," ");
            tempa[i][0] = Integer.parseInt(s.nextToken());
            tempa[i][1] = Integer.parseInt(s.nextToken());
            }


        ///////////////////정렬함//////////////////////////
        Arrays.sort(tempa,new Comparator<int []>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });

        int cnt=1;

        for (int i = 0; i < N; i++) {
            for (int j = i+1; j < N; j++) {
                if(tempa[i][1] < tempa[j][0])
                {
                    cnt++;
                    i=j-1;
                    break;
                }
            }
        }
        System.out.println(cnt);
    }
}