【题解】P1663-山

· · 题解

本题前置知识 :

  1. 斜率 ( Slope ) :当直线L的斜率存在时,对于一次函数 y = kx + b (斜截式),k即该函数图像的斜率。
  2. 二分答案(这应该不用说吧,来做蓝题的人应该都会)

题意

给出n个点相连形成一条折线。
要求找到一个点使得它位于每一段线段的上方且y值最小。

如何理解在每一条线段上方呢?

思路

代码

#include<bits/stdc++.h>
using namespace std;
const int M(5e3+1);
int n;
double x[M],y[M],slope[M],b[M],ans;
inline bool check(double x){
    double L(-2e9),R(2e9);
    for(register int i(2);i<=n;++i)
    {
        if(slope[i]<0) L=max(L,(x-b[i])/slope[i]);
        else{
            if(slope[i]>0) R=min(R,(x-b[i])/slope[i]);
            else if(x<b[i]) return 0;
        }
    }
    return L<=R;
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n;
    for(register int i(1);i<=n;++i){
        cin>>x[i]>>y[i];
        slope[i]=(y[i]-y[i-1])/(x[i]-x[i-1]);
        b[i]=y[i]-slope[i]*x[i];
    }
    register double l(0),r(2e9+1);
    while(l<=r){
        double mid=(l+r)/2;
        if(check(mid))r=mid-0.0001,ans=mid;
        else l=mid+0.0001;
    }
    printf("%.2lf",ans);
    return 0;
}

补充说明