程序设计与算法(一)第11周测验(2019夏季)

本文探讨了两个有趣的计算问题:一是如何通过二分查找法确定从多个圆形区域中分配特定数量的派的最大可能尺寸;二是如何在限定月份数下找到将开销合理分配至各月的最大值。通过具体的算法实现,展示了二分查找法在解决此类问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值