본문 바로가기
ALGORITHM/Greedy

[JAVA] 백준 11399번

by sjs_2215 2019. 6. 4.

[백준 11399] ATM

문제: https://www.acmicpc.net/problem/11399

전형적인 그리디 문제

문제 이해:

각자 번호가 있고, 각 번호마다 할애하는 시간이 주어진다.

고객을 어떻게 세우냐에 따라 시간의 합을 조절할 수 있는데, 최소의 시간의 합을 구하기.

하고자 하는 것:

  • 그 순간순간에 제일 시간이 적게 걸리는 사람들을 채택.

: input된 시간들 배열에 저장. 배열 Array.sort().

  • 걸리는 시간들을 다 더한 result 도출

: += 이용

package till;
import java.util.Arrays;
import java.util.Scanner;


public class Main {
   public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      int n= scan.nextInt();//사람 수 input 저장

      int minutes[] = new int[n+1];//시간들 저장할 배열

      for(int i=0;i<n;i++){//시간 input n개 저장
        minutes[i]=scan.nextInt();  
      }

      int result = Greedy_line(minutes);
      System.out.println(result);
   }

   public static int Greedy_line(int x[]) {
      int total=0;

      Arrays.sort(x);
      int temp=0;
      for(int i=0;i<x.length;i++){
          temp+=x[i];
          total+=temp;
      }

      return total;

   }


}

스터디 조원과 코드 비교중 내 코드가 훨씬 느리다는 것을 알게됨
혹시나 해서 BufferedReader로 바꾸어보니 속도 차이가 어마어마하다는 걸 알게됨
알고는 있었는데 이렇게 몸소 체험한 건 또 처음

채점번호: 13664817 -> bufferedreader 사용
채점번호: 13664762 -> scanner 사용

아래 코드는 똑같은 코드인데 scanner를 bufferedreader로 바꾸어준 코드

import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
   public static void main (String[] args) throws Exception{
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = null;
      int n= Integer.parseInt(br.readLine());//사람 수 input 저장

      int minutes[] = new int[n+1];//시간들 저장할 배열

      st = new StringTokenizer(br.readLine());
      for(int i=0;i<n;i++){//시간 input n개 저장
        minutes[i]=Integer.parseInt(st.nextToken()); 
      }

      int result = Greedy_line(minutes);
      System.out.println(result);
   }

   public static int Greedy_line(int x[]) {
      int total=0;

      Arrays.sort(x);
      int temp=0;
      for(int i=0;i<x.length;i++){
          temp+=x[i];
          total+=temp;
      }

      return total;

   }


}

'ALGORITHM > Greedy' 카테고리의 다른 글

Greedy 수업 필기  (0) 2018.12.17

Comments