跳石头
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=50010;
ll d[N];
int ans;
int main(){
int n,m;
ll l;
cin>>l>>n>>m;
for(int i=1;i<=n;i++) cin>>d[i];
ll left=0,right=l;
while(left<=right){
ll mid=(left+right)/2;
int now=0,s=0;
for(int i=1;i<=n;i++){
if(d[i]-d[now]<mid) s++;
else now=i;
}
if(s<=m){
ans=mid;
left=mid+1;
}
else right=mid-1;
}
cout<<ans<<endl;
return 0;
}
一元三次方程求解
#include <bits/stdc++.h>
using namespace std;
double a,b,c,d;
double f(double x){
return a*pow(x,3)+b*pow(x,2)+c*x+d;
}
double ef(double l,double r){
if(f(l)==0) return l;
if(f(r)==0) return r;
while(r-l>=0.001){
double mid=(l+r)/2;
if(f(mid)==0) return mid;
else {
if(f(l)*f(mid)<0) r=mid;
else l=mid;
}
}
return l;
}
int main(){
cin>>a>>b>>c>>d;
for(double i=-100;i<100;i++){
if(!f(i)) printf("%.2lf ",i);
else if(f(i)*f(i+1)<0){
printf("%.2lf ",ef(i,i+1));
}
}
return 0;
}
烦恼的高考志愿
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int st[N];
int sc[N];
long long ans;
int main(){
int n,m;
cin>>m>>n;
for(int i=0;i<m;i++) cin>>sc[i];
for(int i=0;i<n;i++) cin>>st[i];
sort(sc,sc+m);
for(int i=0;i<n;i++){
int pos;
pos=lower_bound(sc,sc+m,st[i]) - sc;
if(pos==0) {
ans+=abs(st[i]-sc[0]);
continue;
}
else if(pos==m) {
ans+=abs(st[i]-sc[m-1]);
continue;
}
else {
ans+=min(abs(st[i]-sc[pos]),abs(st[i]-sc[pos-1]));
continue;
}
}
cout<<ans<<endl;
return 0;
}
木材加工
#include <bits/stdc++.h>
using namespace std;
long long n, k;
long long a[1000005];
bool f(long long x) {
long long ans = 0;
for (int i = 1; i <= n; i++) {
ans += a[i] / x;
}
return ans >= k;
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
long long l = 0, r = 100000001;
long long mid;
while (l + 1 < r) {
mid = (l + r) / 2;
if (f(mid)) l = mid;
else r = mid;
}
cout << l << endl;
return 0;
}