• 【模板】三分——cf1355E


    发现自己以前的三分模板有问题。。换个标准的!

    //整数三分
    int l = 1,r = 100;
    while(l < r) {
        int lmid = l + (r - l) / 3;
        int rmid = r - (r - l) / 3;
        lans = f(lmid),rans = f(rmid);
        // 求凹函数的极小值
        if(lans <= rans) r = rmid - 1;
        else l = lmid + 1;
        // 求凸函数的极大值
        if(lasn >= rans) l = lmid + 1;
        else r = rmid - 1;
    }
    // 求凹函数的极小值
    cout << min(lans,rans) << endl;
    // 求凸函数的极大值
    cout << max(lans,rans) << endl;
    //浮点三分
    const double EPS = 1e-9;
    while(r - l < EPS) {
        double lmid = l + (r - l) / 3;
        double rmid = r - (r - l) / 3;
        lans = f(lmid),rans = f(rmid);
        // 求凹函数的极小值
        if(lans <= rans) r = rmid;
        else l = lmid;
        // 求凸函数的极大值
        if(lans >= rans) l = lmid;
        else r = rmid;
    }
    // 输出 l 或 r 都可
    cout << l << endl;

    本题代码

    #include<bits/stdc++.h>
    using namespace std;
    #define N 200005
    #define ll long long
    
    ll n,a,r,m,h[N];
    
    ll f(ll x){//所有高度变成x
        ll c1=0,c2=0; 
        for(int i=1;i<=n;i++) 
            if(h[i]<=x)c1+=x-h[i];
            else c2+=h[i]-x;
        ll res=0;
        if(m<a+r){
            ll t=min(c1,c2);
            res+=m*t;
            c1-=t;c2-=t;
        }
        res+=a*c1+r*c2;
        return res;
    }
    
    int main(){
        cin>>n>>a>>r>>m;
        for(int i=1;i<=n;i++)cin>>h[i];
        sort(h+1,h+1+n);
        ll L=0,R=h[n],midl,midr,ans=0;
        while(L<R){
            midl=L+(R-L)/3;
            midr=R-(R-L)/3;
            ll res1=f(midl),res2=f(midr);
            if(res1<=res2){
                ans=res1;R=midr-1;
            }else {
                ans=res2;L=midl+1;
            }
        }
        cout<<ans<<'
    ';
    }
  • 相关阅读:
    New Skateboard
    Mike and strings
    C语言异或运算在程序设计中的妙用
    快速排序
    贪心算法
    快速排序过程分析
    深度搜索C语言伪代码
    matlab 中“newff” 函数的参数设置
    一维小波分解与去噪重构
    matlab绘图(详细)(全面)
  • 原文地址:https://www.cnblogs.com/zsben991126/p/12916489.html
Copyright © 2020-2023  润新知