๐ŸŒท๐ŸŒผ๋ชจ์—ฌ๋ด์š” ๊ฐœ๋ฐœ์˜์ˆฒ๐ŸŒท๐ŸŒผ

[JAVA/์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ์”จ๋ฆ„ ์„ ์ˆ˜(Greedy Algorithm) ๋ณธ๋ฌธ

๊ฐœ๋ฐœ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด JAVA

[JAVA/์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ์”จ๋ฆ„ ์„ ์ˆ˜(Greedy Algorithm)

์š”์ผ์ด 2022. 2. 12. 00:09
๋ฐ˜์‘ํ˜•

์„ค๋ช…

ํ˜„์ˆ˜๋Š” ์”จ๋ฆ„ ๊ฐ๋…์ž…๋‹ˆ๋‹ค. ํ˜„์ˆ˜๋Š” ์”จ๋ฆ„ ์„ ์ˆ˜๋ฅผ ์„ ๋ฐœ๊ณต๊ณ ๋ฅผ ๋ƒˆ๊ณ , N๋ช…์˜ ์ง€์›์ž๊ฐ€ ์ง€์›์„ ํ–ˆ์Šต๋‹ˆ๋‹ค.

ํ˜„์ˆ˜๋Š” ๊ฐ ์ง€์›์ž์˜ ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ ์ •๋ณด๋ฅผ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

ํ˜„์ˆ˜๋Š” ์”จ๋ฆ„ ์„ ์ˆ˜ ์„ ๋ฐœ ์›์น™์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.

“A๋ผ๋Š” ์ง€์›์ž๋ฅผ ๋‹ค๋ฅธ ๋ชจ๋“  ์ง€์›์ž์™€ ์ผ๋Œ€์ผ ๋น„๊ตํ•ด์„œ ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ ๋ชจ๋‘ A์ง€์›์ž ๋ณด๋‹ค ๋†’์€(ํฌ๊ณ , ๋ฌด๊ฒ๋‹ค) ์ง€์›์ž๊ฐ€

์กด์žฌํ•˜๋ฉด A์ง€์›์ž๋Š” ํƒˆ๋ฝํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์„ ๋ฐœ๋œ๋‹ค.”

N๋ช…์˜ ์ง€์›์ž๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ์œ„์˜ ์„ ๋ฐœ์›์น™์œผ๋กœ ์ตœ๋Œ€ ๋ช‡ ๋ช…์˜ ์„ ์ˆ˜๋ฅผ ์„ ๋ฐœํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋‚ด๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ง€์›์ž์˜ ์ˆ˜ N(5<=N<=30,000)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ N๋ช…์˜ ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ ์ •๋ณด๊ฐ€ ์ฐจ๋ก€๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๊ฐ’์€ 1,000,000์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์”จ๋ฆ„ ์„ ์ˆ˜๋กœ ๋ฝ‘ํžˆ๋Š” ์ตœ๋Œ€ ์ธ์›์„ ์ถœ๋ ฅํ•˜์„ธ์š”.

์˜ˆ์‹œ ์ž…๋ ฅ 1 

5
172 67
183 65
180 70
170 72
181 60

 

์˜ˆ์‹œ ์ถœ๋ ฅ 1

3

ํžŒํŠธ

์ถœ๋ ฅ์„ค๋ช…

(183, 65), (180, 70), (170, 72) ๊ฐ€ ์„ ๋ฐœ๋ฉ๋‹ˆ๋‹ค. (181, 60)์€ (183, 65)๋ณด๋‹ค ํ‚ค์™€ ๋ชธ๋ฌด๊ฒŒ ๋ชจ๋‘ ๋‚ฎ๊ธฐ ๋•Œ๋ฌธ์— ํƒˆ๋ฝ์ด๊ณ , (172, 67)์€ (180, 70) ๋•Œ๋ฌธ์— ํƒˆ๋ฝ์ž…๋‹ˆ๋‹ค.

 

 

 

 

import java.util.*;

class Body implements Comparable<Body>{

    public int height;
    public int weight;

    Body(int height, int weight){
        this.height = height;
        this.weight = weight;
    }

    @Override
    public int compareTo(Body o){
        if(this.height==o.height) {
            return o.weight - this.weight;
        }else{
            return o.height - this.height;
        }
    }

}


public class Main {

    static int[][] array;

    public int solution(int n, ArrayList<Body> body) {

        int result = 0;
        int max = 0;

        for(int i=0; i<n; i++){
            if(max<body.get(i).weight){
                max = body.get(i).weight;
                result++;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Main main = new Main();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();

        ArrayList<Body> body = new ArrayList<>();

        for(int i=0; i<n; i++){
            Body tmp = new Body(kb.nextInt(), kb.nextInt());
            body.add(tmp);
        }

        Collections.sort(body);

        System.out.println(main.solution(n, body));
    }

}
Comments