Binary search
Binary search :( board left and right to open and close)
for the other half of the case can refer https://blog.csdn.net/CCSGTC/article/details/80586181
In the binary process, always maintain left-right open and closed conditions
void solve(){
sort(heig,heig+n);
int left = 0, right = 1000000001; // [0,1000000001)
while(left+1<right){
int mid = (left+right)/2;
if(fuc(mid)) left = mid;
else right = mid;
}
printf("%d\n",left);
}
The final boundary conditions:
(Source) https://oi-wiki.org//basic/binary/
half naked title https://www.luogu.org/problemnew/show/P1873
Half of them the possibility to
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n,m;
int heig[1000010];
void get_data(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++){
scanf("%d",&heig[i]);
}
}
bool fuc(int mid){
long long ans = 0;
for(int i=n-1;heig[i]>mid;i--){
ans += heig[i]-mid;
}
return ans>=m;
}
void solve(){
sort(heig,heig+n);
int left = 0, right = 1000000001;
while(left+1<right){
int mid = (left+right)/2;
if(fuc(mid)) left = mid;
else right = mid;
}
printf("%d\n",left);
}
int main() {
get_data();
solve();
return 0;
}
Fractional Programming
Basis: https://blog.csdn.net/hzoi_ztx/article/details/54898323
Bare question: https://vjudge.net/problem/POJ-2976
Reminded program exits conditions (all tears ah)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int n,k;
int a[1010],b[1010];
void get_data(){
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++) cin>>b[i];
}
bool judge(double mid){
double result[1010];
double ans = 0;
for(int i=0;i<n;i++) result[i] = a[i] - mid*b[i];
sort(result,result+n);
for(int i=n-1;i>=k;i--) ans += result[i];
return ans>=0;
}
void solve(){
double left = 0, right = 1e8;
while(right-left>1e-6){
double mid = (right+left)/2;
if(judge(mid)) left = mid;
else right = mid;
}
printf("%.0lf\n",100*left);
}
int main(){
while(cin>>n>>k&&n!=0){ //k是可以等于0而不退出的,,我靠(卡了我2个小时)
get_data();
solve();
}
return 0;
}