programmers, ๋‹จ์†์นด๋ฉ”๋ผ

2021. 12. 3. 22:44ใ†ETC/Algorithm

๐Ÿ”— ๋ฌธ์ œ ๋งํฌ

Greedy - Activity Selection ๊ด€๋ จ ๋ฌธ์ œ!

 

๋ฌธ์ œ ์„ค๋ช…

 

๊ณ ์†๋„๋กœ๋ฅผ ์ด๋™ํ•˜๋Š” ๋ชจ๋“  ์ฐจ๋Ÿ‰์ด ๊ณ ์†๋„๋กœ๋ฅผ ์ด์šฉํ•˜๋ฉด์„œ ๋‹จ์†์šฉ ์นด๋ฉ”๋ผ๋ฅผ ํ•œ ๋ฒˆ์€ ๋งŒ๋‚˜๋„๋ก ์นด๋ฉ”๋ผ๋ฅผ ์„ค์น˜ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

๊ณ ์†๋„๋กœ๋ฅผ ์ด๋™ํ•˜๋Š” ์ฐจ๋Ÿ‰์˜ ๊ฒฝ๋กœ routes๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๋ชจ๋“  ์ฐจ๋Ÿ‰์ด ํ•œ ๋ฒˆ์€ ๋‹จ์†์šฉ ์นด๋ฉ”๋ผ๋ฅผ ๋งŒ๋‚˜๋„๋ก ํ•˜๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ๋Œ€์˜ ์นด๋ฉ”๋ผ๋ฅผ ์„ค์น˜ํ•ด์•ผ ํ•˜๋Š”์ง€๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ

  • ์ฐจ๋Ÿ‰์˜ ๋Œ€์ˆ˜๋Š” 1๋Œ€ ์ด์ƒ 10,000๋Œ€ ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • routes์—๋Š” ์ฐจ๋Ÿ‰์˜ ์ด๋™ ๊ฒฝ๋กœ๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฉฐ routes[i][0]์—๋Š” i๋ฒˆ์งธ ์ฐจ๋Ÿ‰์ด ๊ณ ์†๋„๋กœ์— ์ง„์ž…ํ•œ ์ง€์ , routes[i][1]์—๋Š” i๋ฒˆ์งธ ์ฐจ๋Ÿ‰์ด ๊ณ ์†๋„๋กœ์—์„œ ๋‚˜๊ฐ„ ์ง€์ ์ด ์ ํ˜€ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ์ฐจ๋Ÿ‰์˜ ์ง„์ž…/์ง„์ถœ ์ง€์ ์— ์นด๋ฉ”๋ผ๊ฐ€ ์„ค์น˜๋˜์–ด ์žˆ์–ด๋„ ์นด๋ฉ”๋ผ๋ฅผ ๋งŒ๋‚œ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•ฉ๋‹ˆ๋‹ค.
  • ์ฐจ๋Ÿ‰์˜ ์ง„์ž… ์ง€์ , ์ง„์ถœ ์ง€์ ์€ -30,000 ์ด์ƒ 30,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ

routes return
[[-20,-15], [-14,-5], [-18,-13], [-5,-3]] 2

 

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

-5 ์ง€์ ์— ์นด๋ฉ”๋ผ๋ฅผ ์„ค์น˜ํ•˜๋ฉด ๋‘ ๋ฒˆ์งธ, ๋„ค ๋ฒˆ์งธ ์ฐจ๋Ÿ‰์ด ์นด๋ฉ”๋ผ๋ฅผ ๋งŒ๋‚ฉ๋‹ˆ๋‹ค.

-15 ์ง€์ ์— ์นด๋ฉ”๋ผ๋ฅผ ์„ค์น˜ํ•˜๋ฉด ์ฒซ ๋ฒˆ์งธ, ์„ธ ๋ฒˆ์งธ ์ฐจ๋Ÿ‰์ด ์นด๋ฉ”๋ผ๋ฅผ ๋งŒ๋‚ฉ๋‹ˆ๋‹ค.

 

 

๋ฌธ์ œ ํ•ด๊ฒฐ

 

C++

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(vector<int> a, vector<int> b) { return a[0] < b[0]; }

int solution(vector<vector<int>> routes) {
    int answer = 1;
    sort(routes.begin(), routes.end(), compare);
    int end = routes[0][1];
    
    for (int i = 1; i < routes.size(); i++) {
        if (routes[i][0] > end) {
            end = routes[i][1];
            answer++;
        } else if (routes[i][1] < end) {
            end = routes[i][1];
        }
    }
    return answer;
}

 

์‹œ์ž‘ ์ง€์ ์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•œ ํ›„, ์ข…๋ฃŒ ์‹œ์ ๋ณด๋‹ค ํฐ ์‹œ์ž‘ ์ง€์ ์ด ๋‚˜์˜ฌ ๋•Œ๊นŒ์ง€ ํ•œ ๋ฌถ์Œ(๋‹จ์†์นด๋ฉ”๋ผ ํ•œ๋Œ€๋กœ ํฌํ•จํ•  ์ˆ˜ ์žˆ๋Š” ์ฐจ๋Ÿ‰ ๋ชจ์Œ)์œผ๋กœ  ๊ณ„์‚ฐํ•œ๋‹ค.