Algorithm/Baekjoon

[BOJ 2110] ๊ณต์œ ๊ธฐ ์„ค์น˜

sun_young 2024. 3. 14. 00:28

๐Ÿ“ƒ ๋ฌธ์ œ

https://www.acmicpc.net/problem/2110

 

2110๋ฒˆ: ๊ณต์œ ๊ธฐ ์„ค์น˜

์ฒซ์งธ ์ค„์— ์ง‘์˜ ๊ฐœ์ˆ˜ N (2 ≤ N ≤ 200,000)๊ณผ ๊ณต์œ ๊ธฐ์˜ ๊ฐœ์ˆ˜ C (2 ≤ C ≤ N)์ด ํ•˜๋‚˜ ์ด์ƒ์˜ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ์ง‘์˜ ์ขŒํ‘œ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” xi (0 ≤ xi ≤ 1,000,000,000)๊ฐ€

www.acmicpc.net


๐Ÿ’ป ์ฝ”๋“œ

#include <iostream>
#include <algorithm>
using namespace std;

int N, M;
int arr[200001];

int main() {
	cin >> N >> M;

	for (int i = 0; i < N; i++) cin >> arr[i];
	sort(arr, arr + N);

	int start = 1;
	int end = arr[N - 1] - arr[0];
	int mid = 0;
	int result = 0;

	while (start <= end) {
		mid = (start + end) / 2;

		int cnt = 1; // ๋ฐฐ์น˜๋œ ๊ณต์œ ๊ธฐ ๊ฐœ์ˆ˜
		int temp = 0;
		for (int i = 1; i < N; i++) {
			int len = arr[i] - arr[temp];
			if (len >= mid) {
				cnt++;
				temp = i;
			}
		}

		if (cnt < M) end = mid - 1;
		else {
			result = mid;
			start = mid + 1;
		}
	}
	cout << result << '\n';
}

 

๋ฉ”๋ชจ๋ฆฌ ๋ฐ ์‹œ๊ฐ„


๐Ÿ’ก ํ’€์ด

 

๊ฐ€์žฅ ์ธ์ ‘ํ•œ ๋‘ ๊ณต์œ ๊ธฐ ์‚ฌ์ด์˜ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ œ์ผ ์ฒซ๋ฒˆ์งธ ์ง‘์—๋Š” ๋ฌด์กฐ๊ฑด ๊ณต์œ ๊ธฐ๋ฅผ ์„ค์น˜ํ•  ๊ฒƒ → ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๊ฐ€ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ์Œ

 

 

int cnt = 1; // ๋ฐฐ์น˜๋œ ๊ณต์œ ๊ธฐ ๊ฐœ์ˆ˜
	int temp = 0;
	for (int i = 1; i < N; i++) {
		int len = arr[i] - arr[temp];
		if (len >= mid) {
			cnt++;
			temp = i;
	}
}

 

temp๋Š” ๋งˆ์ง€๋ง‰์œผ๋กœ ๊ณต์œ ๊ธฐ๊ฐ€ ์„ค์น˜๋œ ์ขŒํ‘œ๊ฐ€ ์ €์žฅ๋œ ์ธ๋ฑ์Šค

 

- ๋งˆ์ง€๋ง‰์œผ๋กœ ์„ค์น˜๋œ ๊ณต์œ ๊ธฐ ์œ„์น˜์™€ ํ˜„์žฌ ์ง‘์˜ ์ขŒํ‘œ๋ฅผ ๋น„๊ตํ•˜์—ฌ mid, ์ฆ‰ ์ตœ๋Œ€๊ฑฐ๋ฆฌ๋กœ ๊ฐ€์ •ํ•œ ๊ฑฐ๋ฆฌ๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด ํ•ด๋‹น ์ง‘์˜ ์ขŒํ‘œ์— ๊ณต์œ ๊ธฐ ์„ค์น˜๊ฐ€ ๊ฐ€๋Šฅ

- ๊ณต์œ ๊ธฐ ์„ค์น˜ ํ›„ temp ๊ฐ’์€ ๋งˆ์ง€๋ง‰์œผ๋กœ ์„ค์น˜๋œ ๊ณต์œ ๊ธฐ ์ขŒํ‘œ(i)๋กœ ๊ฐฑ์‹  ๋ฐ ์„ค์น˜๋œ ๊ณต์œ ๊ธฐ ๊ฐœ์ˆ˜(cnt)๋ฅผ ์ฆ๊ฐ€

 

if (cnt < M) end = mid - 1;
	else {
		result = mid;
		start = mid + 1;
}

 

- ์„ค์น˜ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ณต์œ ๊ธฐ ๊ฐœ์ˆ˜(M)๋ณด๋‹ค ํ˜„์žฌ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋กœ ๊ฐ€์ •ํ•œ ๊ฐ’(mid)์—์„œ ์„ค์น˜๋œ ๊ณต์œ ๊ธฐ ๊ฐœ์ˆ˜(cnt)๊ฐ€ ๋” ์ž‘์œผ๋ฉด ๊ฑฐ๋ฆฌ๋ฅผ ์ค„์ธ๋‹ค

- cnt๊ฐ€ ๋” ํฌ๋ฉด result๋ฅผ ๊ฐฑ์‹ ํ•˜๊ณ  ๊ฑฐ๋ฆฌ๋ฅผ ๋” ๋Š˜๋ฆฐ ํ›„ ๋‹ค์‹œ ๊ณ„์‚ฐํ•œ๋‹ค