这题也是二分穷举的思路。
上下界调整不能mid+1或mid-1了,这样会损失精度。因为不是整型。
还有就是浮点数的相等比较不能像整型那样用==,还是设置一个逼近区间比较好。如
while(high-low>1e-5)
不然的话,是有可能无限循环的。
或者在每次调整上下界的时候进行微调,如
while(low<high){
double mid = (low+high)/2;
if(valid(mid))
low = mid+1e-5;
else
high = mid-1e-5;
}
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define PI 3.14159265359
int N,F;
double V[10000];
double low,high;
bool valid(double mid){
int count = 0;
for(int i=0;i<N;++i){
count += (int)(V[i]/mid);
}
return count >= F+1;
}
void process(){
while(high-low>1e-5){
double mid = (low+high)/2;
if(valid(mid))
low = mid;
else
high = mid;
}
printf("%.4f\n",low*PI);
}
int main(){
int t;
double r;
double sum;
cin>>t;
while(t--){
cin>>N>>F;
sum = 0;
for(int i=0;i<N;++i){
cin>>r;
V[i] = r*r;
sum += V[i];
}
low = 0;
high = sum/(double)(F+1);
process();
}
return 0;
}