티스토리 뷰

알고리즘/Java

[JUNGOL] 1828 냉장고

세진짱 2020. 2. 12. 09:56

 

그리디 문제다 정렬을 시키고 뒤에 화학물질부터 보면된다

냉장고의 (x,y)라고 할 때 y를 기준으로 잡고 다음 화학물질의 x가

현재 y를 넘는지 안넘는지로 판단할 수 있다

 

넘는다면 같은 냉장고안에 넣을 수 있다

그리고 y값은 더 뒤에있는 값으로 초기화해준다

 

그리고 범위를 안넘으면 냉장고를 늘려주면 된다!

 

자바는 pair가 없어서 구현해야한다..!

그리고 pq는 minheap이다!!

 

JAVA 소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
 
class Pair implements Comparable<Pair> {
    int first, second;
    
    Pair(int f, int s) {
        this.first = f;
        this.second = s;
    }
    
    public int compareTo(Pair p) {
        if(this.first > p.first) {
            return -1
        }
        else if(this.first == p.first) {
            if(this.second > p.second) {
                return -1;
            }
        }
        return 1
    }
}
 
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n =sc.nextInt();
        PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
        
        for(int i=0;i<n;i++) {
            int x=sc.nextInt();
            int y=sc.nextInt();
            x+=300; y+=300;
            Pair p = new Pair(y,x);
            pq.add(p);
        }
        int ans=1;
        int pos = pq.poll().second;
        while(!pq.isEmpty()) {
            int x = pq.peek().first;
            int y = pq.poll().second;
            if(x>=pos) pos = Math.max(pos, y);
            else {
                ans+=1; pos=y;
            }
        }
        System.out.println(ans);    
    }
}
 
 
 

 

C++로도 먼저 풀어봤다..!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int n;
 
int main() {
    scanf(" %d"&n);
    priority_queue<pair<intint>> pq;
 
    for (int i = 0; i < n; i++) {
        int x, y; scanf(" %d %d"&x, &y);
        x += 300; y += 300;
        pq.push({ y,x });
    }
    int ans = 1;
 
    int pos = pq.top().second; pq.pop();
    while (!pq.empty()) {
        int x = pq.top().first;
        int y = pq.top().second;
        pq.pop();
        if (x >= pos) pos = max(pos, y);
        else {
            ans += 1; pos = y;
        }
    }
    printf("%d\n", ans);
}
 
 

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

[SWEA] 9659 다항식 계산  (0) 2020.04.03
[SWEA] 1244 최대상금  (0) 2020.02.17
[SWEA] 1233 사칙연산 유효성 검사  (0) 2020.02.11
[SWEA] 8931 제로  (0) 2020.01.21
[SWEA] 9229 한빈이와 SpotMart  (0) 2020.01.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함