개?발/SWEA

SWEA 20728. 공평한 분배 2

YUEIC 2025. 5. 23. 19:55

1. 차이가 가장 적게 나는 경우를 구해야 함. (본인의 경우 제일 큰 주머니에서 n번째로 작은 주머니를 뺐음)

2. 오름차순으로 정렬해서 배열의 0번째부터 끝까지 진행하며 차이를 구한다. (슬라이딩 윈도우)

 

import java.util.Arrays;
import java.util.Scanner;

public class Swea20728FairDistribution2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        sc.nextLine();

        int[] answer = new int[t];

        for(int tc = 0 ; tc < t ; tc++){
            String[] line1 = sc.nextLine().split(" ");
            String[] line2 = sc.nextLine().split(" ");
            
            //배열 생성
            int[] pocket = new int[Integer.parseInt(line1[0])];

            for(int i = 0 ; i < pocket.length ;i++){
                pocket[i] = Integer.parseInt(line2[i]);
            }

            //배열 오름차순 정렬
            Arrays.sort(pocket);

            //최소 차이를 저장할 변수
            int min = 0;

            //(i + 주머니개수) - i 가 가장 작은 수를 저장할 수 있도록 반복문을 구성(슬라이딩 윈도우)
            for(int i = 0 ; i <= pocket.length - Integer.parseInt(line1[1]); i++){
                int diff = pocket[i + Integer.parseInt(line1[1]) - 1] - pocket[i];
                if(min == 0 || diff < min){
                    min = diff;
                }
            }

            answer[tc] = min;
        }

        for(int i = 0 ; i< answer.length ; i++){
            System.out.println("#" + (i + 1) + " " + answer[i]);
        }

        sc.close();
    }
 

Java_Problem/Swea20728FairDistribution2.java at main · YUEIZIA/Java_Problem

Contribute to YUEIZIA/Java_Problem development by creating an account on GitHub.

github.com

 

'개?발 > SWEA' 카테고리의 다른 글

SWEA 20019. 회문의 회문  (0) 2025.05.23
SWEA 20551. 증가하는 사탕 수열  (0) 2025.05.23
SWEA 20955. XY 문자열 1  (0) 2025.05.23
SWEA 20934. 방울 마술  (0) 2025.05.23
SWEA 24001. 로봇 언어  (0) 2025.05.22