슈콩

[SWEA] 공평한 분배 2 본문

Algorithms/SWEA

[SWEA] 공평한 분배 2

shukong 2025. 11. 15. 14:58

 

 

[문제]

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AY6cg0MKeVkDFAXt

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

 

 

[소스 코드]

// 시간 초과 발생 : 모든 경우의 수 불가

import java.io.*;
import java.util.*;
public class Solution {
	static int n,k,result;
	static int[] pocket;
	static boolean[] visit;
	static int min,max;
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		int T = Integer.parseInt(br.readLine());
		for(int tc=1;tc<=T;tc++) {
			st = new StringTokenizer(br.readLine());
			n = Integer.parseInt(st.nextToken());
			k = Integer.parseInt(st.nextToken());
			pocket = new int[n];
			st = new StringTokenizer(br.readLine());
			for(int i=0;i<n;i++) {
				pocket[i] = Integer.parseInt(st.nextToken());
			}
			visit = new boolean[n];
			result = Integer.MAX_VALUE;
			min = Integer.MAX_VALUE;
			max = Integer.MIN_VALUE;
			combi(0);
			System.out.println("#"+tc+" "+result);
		}
	}
	private static void combi(int cnt) {
		if(cnt==k) {
			for(int i=0;i<n;i++) {
				if(visit[i]) {
					min = Math.min(min, pocket[i]);
					max = Math.max(max, pocket[i]);
				}
			}
			result = Math.min(result, max - min);
			return;
		}
		for(int i=0;i<n;i++) {
			if(!visit[i]) {
				visit[i] = true;
				combi(cnt+1);
				visit[i] = false;
			}
		}
	}
}

 

// 정렬 후, 구간 내 가장 작은 값 return

import java.io.*;
import java.util.*;
public class Solution {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		int T = Integer.parseInt(br.readLine());
		for(int tc=1;tc<=T;tc++) {
			st = new StringTokenizer(br.readLine());
			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			int[] pocket = new int[n];
			st = new StringTokenizer(br.readLine());
			for(int i=0;i<n;i++) {
				pocket[i] = Integer.parseInt(st.nextToken());
			}
			Arrays.sort(pocket);
			int result = Integer.MAX_VALUE;
			for(int i=0;i<=n-k;i++) {
				result = Math.min(result, pocket[i+k-1] - pocket[i]);
			}
			System.out.println("#"+tc+" "+result);
		}
	}
}

'Algorithms > SWEA' 카테고리의 다른 글

[SWEA] 팰린드롬 문제  (0) 2025.11.15
[SWEA] 화섭이의 정수 나열  (0) 2025.11.15
[SWEA] 사랑의 카운슬러  (0) 2025.11.15
[SWEA] 신뢰  (0) 2025.11.15
[SWEA] 알파벳 공부  (0) 2025.11.14