알고리즘

C++ 알고리즘 - 백준 1654 랜선 자르기 (이분/매개변수 탐색)

마루설아 2025. 1. 4. 16:45

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

 

#include <bits/stdc++.h>
#define endl "\n"

using namespace std;

int main(void) {
	// C++ Init
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	int input1, input2;
	int num;
	vector<int> v;
	cin >> input1 >> input2;

	for (int i = 0; i < input1; i++) {
		cin >> num;
		v.push_back(num);
	}

	sort(v.begin(), v.end());

	long left = 1;
	long right = v[v.size() - 1];
	long mid;
	int cnt;
	int answer;

	while (left <= right) {
		cnt = 0;
		mid = (left + right) / 2;

		for (int i = 0; i < v.size(); i++) {
			cnt += v[i] / mid;
		}

		if (cnt >= input2) {
			answer = mid;
			left = mid + 1;
		}

		else {
			right = mid - 1;
		}
	}

	cout << answer;
}