1. 程式人生 > 實用技巧 >AtCoder Regular Contest 100 C - Linear Approximation

AtCoder Regular Contest 100 C - Linear Approximation

題意 給你一堆x軸上的點

然後讓你在x軸找一個點,使所有點到他的距離總和最小

考慮之前那個所有點都是x,y表示的題

那個題顯然是個二次函式

這個題也是求距離,就套三分算一算,

#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define io std::ios::sync_with_stdio(false)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pii;
const double
pi=acos(-1); const ll P = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} ll qpow(ll a,ll n){ll r=1%P;for (a%=P; n; a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} const double eps=1e-5; ll lcm(ll a,ll b){return a*b/gcd(a,b);} const int maxn=2e5+10; int a[maxn]; int n; ll check(
int x) { ll ans=0; for(int i=1;i<=n;i++) { ans+=abs(a[i]-x); } return ans; } int main() { cin>>n; int l=-1e9,r=1e9; for(int i=1;i<=n;i++) { cin>>a[i]; a[i]-=i; } while(l<r-1) { int midl=l+r>>1; int midr=midl+r>>1;
if(check(midl)>check(midr)) l=midl; else r=midr; } cout<<min(check(l),check(r))<<endl;//然後這地方有個問題啊,最後再取一下l,r }