C. Discrete Acceleration

不哭的超人發表於2020-10-23

C. Discrete Acceleration

題解:二分。二分列舉距離,分別求出從前往後的時間與從後往前的時間,讓距離近似相等。

#include <iostream>
#include <cstdio>
typedef long long ll;
using namespace std;
const int N = 1e5+10;

double a[N];



int L;
int n;


double get1(double x){
    double pre = 0,t = 0,speed = 1.0;
    for(int i = 1;i <= n;i++){
        if(a[i] <= x){
            t += (a[i]-pre)/speed;
            pre = a[i];
        }else break;
        speed += 1.0;
    }
    t += (x-pre)/speed;
    return t;
}

double get2(double x){
    double pre = L,t = 0,speed = 1.0;
    for(int i = n;i >= 1;i--){
        if(a[i] >= x){
            t += (pre-a[i])/speed;
            pre = a[i];
        }else break;
        speed += 1.0;
    }
    t += (pre-x)/speed;
    return t;
}

void solve(){
    scanf("%d%d",&n,&L);
    for(int i = 1;i <= n;i++){
        scanf("%lf",a+i);
    }

    double l = 0,r = L;
    while(r-l > 1e-6){
        double mid = (l+r)/2.0;
        //cout<<l<<" "<<r<<" "<<mid<<endl;
        double t1 = get1(mid);
        double t2 = get2(mid);
        if(t1 < t2){
            l = mid;
        }else {
            r = mid;
        }
    }
    printf("%.10lf\n",get1(l));
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        solve();
    }
    return 0;
}

相關文章