001:派
#include <iostream>
#include <iomanip>
#include<cstring>
#pragma warning(disable:4996)
using namespace std;
const double EPS = 1.0E-5;
const double PI = 3.141592653589793;
const int NUM = 10000;
double pie[NUM];
double testpie[NUM];
bool feasible(double size, double pie[], int n,int f) {
int sum = 0;
for (int i = 0;i < n;i++)
sum += int(pie[i] / size);
if (sum >= f)
return true;
else
return false;
}
double BinarySearch(double pie[],double limit,int n,int f) {
double l = 0, r=limit,lastSize=0;
while (r - l > EPS) {
double mid = (r + l) / 2;
if (feasible(mid, pie, n,f)) {
lastSize = mid;
l = mid;
}
else
r = mid;
}
return lastSize;
}
int main()
{
//freopen("C:\\Users\\czh\\Desktop\\2.txt", "r", stdin);
int n, f;
cin >> n >> f;
f++;
double limit=0, sum = 0;
for (int i = 0;i < n;i++) {
cin >> pie[i];
pie[i] =pie[i] * pie[i] * PI;
sum += pie[i];
limit = limit < pie[i] ? pie[i] : limit;
}
limit = limit > sum / f ? sum / f : limit;
cout << fixed << setprecision(3) << BinarySearch(pie, limit, n,f);
//printf("%.3f", BinarySearch(pie, limit, n, f));
return 0;
}
002:月度开销
#include<iostream>
#include<cstdlib>
#pragma warning(disable:4996)
using namespace std;
const int NUM = 100000;
int Expense[NUM];
bool IsOk(int n,int m,int Max) {
int sum = 0, count = 1;
for (int i = 0;i < n;i++) {
if (sum + Expense[i] > Max) {
sum = Expense[i];
count++;
}
else
sum += Expense[i];
}
if (count <= m)return true;
else return false;
}
int BinarySearch(int n, int m,int Max,int sum) {
int l = Max, r = sum, lastExp = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (IsOk(n, m, mid)) {
lastExp = mid;
r = mid - 1;
}
else
l = mid + 1;
}
return lastExp;
}
int main()
{
//freopen("C:\\Users\\czh\\Desktop\\2.txt", "r", stdin);
int n, m, Max =0,sum=0;
cin >> n >> m;
for (int i = 0;i < n;i++) {
cin >> Expense[i];
Max = Expense[i] > Max ? Expense[i] : Max;
sum += Expense[i];
}
cout << BinarySearch(n, m, Max, sum);
}