01-24 00:19
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_52 ๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ(๊ฒฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_52 ๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ(๊ฒฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜)

miinsun 2022. 1. 13. 17:20

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

N๊ฐœ์˜ ๋งˆ๊ตฌ๊ฐ„์ด ์ˆ˜์ง์„ ์ƒ์— ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋งˆ๊ตฌ๊ฐ„์€ x1, x2, x3, ......, xN์˜ ์ขŒํ‘œ๋ฅผ ๊ฐ€์ง€๋ฉฐ, ๋งˆ๊ตฌ๊ฐ„ ๊ฐ„์— ์ขŒํ‘œ๊ฐ€ ์ค‘๋ณต๋˜๋Š” ์ผ์€ ์—†์Šต๋‹ˆ๋‹ค.

ํ˜„์ˆ˜๋Š” C๋งˆ๋ฆฌ์˜ ๋ง์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ, ์ด ๋ง๋“ค์€ ์„œ๋กœ ๊ฐ€๊นŒ์ด ์žˆ๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ฐ ๋งˆ๊ตฌ๊ฐ„์—๋Š” ํ•œ ๋งˆ๋ฆฌ์˜ ๋ง๋งŒ ๋„ฃ์„ ์ˆ˜ ์žˆ๊ณ , ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๊ฒŒ ๋ง์„ ๋งˆ๊ตฌ๊ฐ„์— ๋ฐฐ์น˜ํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.

C๋งˆ๋ฆฌ์˜ ๋ง์„ N๊ฐœ์˜ ๋งˆ๊ตฌ๊ฐ„์— ๋ฐฐ์น˜ํ–ˆ์„ ๋•Œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๋Š” ๊ทธ ์ตœ๋Œ€๊ฐ’์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

 

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=200,000)๊ณผ C(2<=C<=N)์ด ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘˜์งธ ์ค„์— ๋งˆ๊ตฌ๊ฐ„์˜ ์ขŒํ‘œ xi(0<=xi<=1,000,000,000)๊ฐ€ ์ฐจ๋ก€๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

5 3
1 2 8 4 9

์ถœ๋ ฅ - ์ฒซ ์ค„์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•˜์„ธ์š”.

3

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	
	public int count(int[] arr, int dist) { //๋งˆ๊ตฌ๊ฐ„ ๊ฐ„์˜ ๊ฑฐ๋ฆฌ์— ํ—ˆ์šฉ๋˜๋Š” ๋ง ์ˆ˜
		int cnt = 1;
		int ep = arr[0];
		
		for(int i = 1; i < arr.length; i++) {
			if(arr[i] - ep >= dist) {
				cnt++;
				ep = arr[i];
			}
		}
		
		return cnt;
	}
	
	public int solution(int n, int c, int[] arr) {
		int answer = 0;
		Arrays.sort(arr);
		
		int lt = 1; // ๋งˆ๊ตฌ๊ฐ„ ๊ฐ„ ๊ฐ€์žฅ ์งง์€ ๊ฑฐ๋ฆฌ
		int rt = arr[n-1]; // ๋งˆ๊ตฌ๊ฐ„ ๊ฐ„ ๊ฐ€์žฅ ๋จผ ๊ฑฐ๋ฆฌ
		while(lt <= rt) {
			int mid = (lt + rt) / 2;
			if(count(arr, mid) >= c) {
				answer = mid;
				lt = mid + 1;
			}
			else
				rt = mid - 1;
		}
		
		return answer;
	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		int c = sc.nextInt();
		
		int [] arr = new int [n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(n, c, arr));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments