三分模板

本文介绍了三分搜索的模板,包括对于整型和浮点型的处理,特别强调了在处理double类型时循环条件的设置,以避免可能出现的死循环问题。此外,还提到了一种限定次数的三分搜索方法,并给出了一道相关的竞赛题目——cf244E. Police Patrol,作为应用场景的示例。

int三分

int calc(int M)
{
    
}
int solve(int L, int R)
{
    int M, RM;
    while (L + 1 < R)
    {
        M = (L + R) / 2;
        RM = (M + R) / 2;
        if (calc(M) < calc(RM)) //计算最小值,若为最大值则>
            R = RM;
        else
            L = M;
    }
    return L;
}

double的三分模板

注意一点,double的循环条件中最好使用以下的表示(L + EPS < R),如果使用dcmp(R - L)> 0判断也可以,但是使用dcmp函数时候一定不能写等号,因为如果两个double数在EPS范围内相等的还继续的话会导致死循环

const double EPS = 1e-10;  
  
double calc(double n)  
{  
    return;  
}  
  
double solve(double L, double R)  
{  
    double M, RM;  
    while (L + EPS < R)  
    {  
        M = (L + R) / 2;  
        RM = (M + R) / 2;  
        if (calc(M) < calc(RM)) //计算最小值  
            R = RM;  
        else  
            L = M;  
    }  
    return L;  
}  

还有一种是限定次数的三分

const double EPS = 1e-10;

double calc(double n)
{
    return;
}

double solve(double L, double R)
{
    double M, RM;
    for (int i = 1; i <= 300; i++)
    {
        M = (L + R) / 2;
        RM = (M + R) / 2;
        if (calc(M) < calc(RM)) R = RM;
        else L = M;
    }
    return L;
}


一个例题

cf244E. Police Patrol

using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 100010;
const int MOD = 1000000007;

int n, m;
int a[1000100];
LL calc(int idx)
{
    LL ans = 0;
    int x = -1, y = -1;
    for (int i = 0; i < idx; i += m)
    {
        ans += (LL)abs(a[i] - a[idx]) * 2;
        x = i;
    }
    for (int i = n - 1; i > idx; i-= m)
    {
        ans += (LL)abs(a[i] - a[idx]) * 2;
        y = i;
    }
    return ans;
}

int solve(int L, int R)
{
    int M, RM;
    while (L + 1 < R)
    {
        M = (L + R) / 2;
        RM = (M + R) / 2;
        if (calc(M) < calc(RM)) //计算最小值
            R = RM;
        else
            L = M;
    }
    return L;
}

int main()
{
    RII(n, m);
    REP(i, n)
    {
        RI(a[i]);
    }
    int ansid = solve(0, n - 1);

    cout << calc(ansid) << endl;
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值