【POJ】[3122]Pie

Problem Description

Loading...

Problem Analysis

Application of the binary search idea
Approaching continuously by bisecting from the maximum value down to 0
to find the maximum possible value

Unlike binary search for a particular number in an array
there is no need to sort the array here
because what is checked is how many pieces can be divided at the current mid
if too few pieces are made, it means the value needs to be smaller
otherwise it means it can be a little larger
repeating this way continuously approaches the correct result

The other thing to pay attention to is
data precision issues

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<stdio.h>
#include<math.h>
//#include<algorithm>
//using namespace std;
double pi=acos(-1.0);
double a[10020];
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n,m;
		scanf("%d %d",&n,&m);
		m++;
		double sum=0;
		for(int i=0; i<n; i++) {
			int t;
			scanf("%d",&t);
			a[i]=t*t;
			sum+=a[i];
		}
//		sort(a,a+n);
//	非常好的一点 这种方式其实不用排序
		double lt=0,rt=sum/m,mid;
		while(rt-lt>0.000001) {
			mid=(lt+rt)/2;
			int cnt=0;
			for(int i=0; i<n; i++) {
				cnt+=(int)(a[i]/mid);
			}
			if(cnt>=m)
				lt=mid;
			else
				rt=mid;
		}
		printf("%.4lf\n",mid*pi);
	}
	return 0;
}

Problem links: 【POJ】[3122]Pie 【HDU】[1969]Pie

Loading...