百度之星初赛(1) 1003 序列变换 二分搜索

本文提供了一段使用C++编写的算法代码,该算法通过二分查找的方式解决了一个具体问题。涉及的主要步骤包括输入一组整数,设定一个阈值,并通过调整这个阈值来确保经过特定操作后的数列不会出现违反条件的情况。最终输出的是能够满足条件的最小阈值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <iostream>
#include <cstring>
#include <set>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;

int n;
int a[100015];
int b[100015];

int fun(int m){
    for(int i = 0;i < n;i++){
        if(i == 0){
            b[i] = a[i]-m;
        }
        else{
            if(a[i]+m < b[i-1]+1){
                return 0;
            }
            else{
                if(a[i]-m < b[i-1]+1){
                    b[i] = b[i-1] + 1;
                }
                else
                {
                    b[i] = a[i] - m;
                }
            }
        }
    }
    return 1;
}
int main(){

    int t;
    cin >> t;
    for(int kcase = 1; kcase <= t;kcase ++){
        scanf("%d",&n); 
        int maxn = 0;
        for(int i = 0;i < n;i++){
            scanf("%d",&a[i]);
            if(a[i] > maxn){
                maxn = a[i];
            }
        }        
        
        int l = 0;
        int r = 1000000+1;
        memset(b,0,sizeof(b));
        while(l < r){
            int m = l + (r-l)/2;
            if(fun(m)){
                r = m;
            }
            else{
                l = m + 1;
            }
        }
        printf("Case #%d:\n",kcase);
        printf("%d\n",l);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值