File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ public class Main {
4+
5+ public static void main (String [] args ) {
6+ // 집의 개수(N)와 공유기의 개수(C)를 입력받기
7+ Scanner sc = new Scanner (System .in );
8+ int n = sc .nextInt ();
9+ int c = sc .nextInt ();
10+
11+ // 전체 집의 좌표 정보를 입력받기
12+ ArrayList <Integer > arr = new ArrayList <>();
13+ for (int i = 0 ; i < n ; i ++) {
14+ arr .add (sc .nextInt ());
15+ }
16+
17+ // 이진 탐색을 위해 정렬 수행
18+ Collections .sort (arr );
19+
20+ int start = arr .get (1 ) - arr .get (0 ); // 집의 좌표 중에 가장 작은 값
21+ int end = arr .get (n - 1 ) - arr .get (0 ); // 집의 좌표 중에 가장 큰 값
22+ int result = 0 ;
23+
24+ while (start <= end ) {
25+ // mid는 가장 인접한 두 공유기 사이의 거리(Gap)을 의미
26+ int mid = (start + end ) / 2 ;
27+ int value = arr .get (0 );
28+ int cnt = 1 ;
29+ // 현재의 mid 값을 이용해 공유기를 설치하기
30+ for (int i = 1 ; i < n ; i ++) { // 앞에서부터 차근차근 설치
31+ if (arr .get (i ) >= value + mid ) {
32+ value = arr .get (i );
33+ cnt += 1 ;
34+ }
35+ }
36+ // C개 이상의 공유기를 설치할 수 있는 경우, 거리를 증가시키기
37+ if (cnt >= c ) {
38+ start = mid + 1 ;
39+ result = mid ; // 최적의 결과를 저장
40+ }
41+ // C개 이상의 공유기를 설치할 수 없는 경우, 거리를 감소시키기
42+ else {
43+ end = mid - 1 ;
44+ }
45+ }
46+ System .out .println (result );
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments