[Coursera]演算法基礎_Week8_二分與貪心_Q1

yiliu_cr發表於2015-12-14
#include <iostream>
#include <set>
#include <string.h>
using namespace std;
set<int> s;
bool f(int n,int C) {
	set<int>::iterator i = s.begin();
	set<int>::iterator j = s.begin();
	C -= 1;
	while (i!=s.end()) {
		i++;
		if (*i - *j >= n) {
			C--;
			if (C == 0)
				break;
			j = i;
		}
	}
	if (C == 0)
		return true;
	else
		return false;
}
int main() {
	int N, C;
	cin >> N >> C;
	int x;
	for (int i = 1; i <= N; i++) {
		cin >> x;
		s.insert(x);
	}
	int up = x / C;
	int down = 1;
	while (down<=up) {
		int mid = (up + down) / 2;
		bool F = f(mid,C);
		if (F)
			down = mid + 1;
		
		else
			up = mid - 1;
	}
	cout << down-1 << endl;
	return 0;
}

相關文章