Binary Search is a very basic algorithm. It is used to determine whether to search for the left half segment or the right half segment based on the size of the median, it is returned when the median value is equal to the number to be found or when the median value meets certain conditions, therefore, when some problems require finding a value that meets certain constraints within a certain range, we can use binary search, time complexity O (log N );
Question: http://acm.hit.edu.cn/hoj/problem/view? Id = 2651
Because the questions have precision requirements, there will be a certain degree of errors for the floating point number decimal part, so you can choose to have the decimal part of the value to expand the E6 times, because the question requires accurate to the E-3, then the result is reduced as required.
#include <iostream>#include <cstdio>#include <cmath>#define pi 3.14159265358979#define MAX 10010using namespace std;long long size[MAX];int c,n,f;bool judge(long long x){ long long m = 0; for(int i = 0;i < n;i++){ m += size[i] / x; } return m >= f;}int main(){ long long high,mid,low,res; int a; cin>>c; while(c --){ cin>>n>>f; f += 1; low = 0; high = 0; res = 0; a = 0; for(int i = 0;i < n;i++){ cin>>a; size[i] = a*a*pi*1000000; high += size[i]; } while(low <= high){ mid = (low + high)/2; if(judge(mid)){ low = mid+1; res = mid; } else high = mid-1; } printf("%.4lf\n",(double)res/1000000); } return 0;}