day2 今天被耽搁+摆烂了

二分系统学习

适用二分的情况

1 确定一个区间,目标值在区间中

2 找一个性质满足

        (1)具有二段性

        (2) 答案是二段性的分界点

整数二分步骤

acwing789

 实数二分

acwing790

#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

int main(){
    double x;
    cin >> x;
    double l = -1000, r = 1000;
    while(r - l > 1e-8) //一般多取两位
    {
     double mid = (l+r)/2;
     if(mid*mid*mid >= x) r = mid
     else l = mid;
    }
    printf("%lf\n",l); //默认保留6位 保留4位的话%.4lf
    
    return 0;
}

二分二段性的思考

机器人跳跃为例子

初试能力为E0 当初始能量为E>E0时是否能满足需求?

答案可能的区间以答案为边界 一半满足一半不满足

acwing730

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>

using namespace std;
const int N = 100010;
int n;
int q[N];

bool check(int e)
{
    for(int i = 0; i < n; i++)
    {
        e = e * 2 - q[i];
        if(e > 1e5) return true;
        if(e < 0) return false;
    }
    return true;
    
}

int main()
{
    scanf("%d",&n);
    for(int i = 0; i < n; i++) scanf("%d",&q[i]);
    int l = 0,r = 1e5;
    while(l<r)
    {
        int mid = (l+r) /2;
        if(check(mid)) r = mid;
        else l = mid + 1;
    }
    cout << l <<endl;
    
    return 0;
}

check函数比较难想需要数学推导+对二段性的理解

acwing1460 我在哪

#include <iostream>
#include <cstring>
#include <algorithm>
#include<unordered_set>

using namespace std;
int n;
string str;

bool check(int mid)
{
    unordered_set<string> hash;

    for(int i = 0; i + mid - 1<n; i++)
    {
        string s = str.substr(i,mid);
        if(hash.count(s)) return false; //判断哈希表中有无重复
        hash.insert(s);//没有重复就加入哈希表
    }
    return true; //没有重复的俩个字符串 mid合法
}

int main(){
    cin >> n >> str;
    int l = 1, r = n;
    while(l < r)
    {
        int mid = l + r >> 1;
        if(check(mid)) r = mid ;
        else l = mid + 1;

    }
    cout << l << endl;

    return 0;
}

作者:爬墙少爷儿
链接:https://www.acwing.com/activity/content/code/content/5898730/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

哈希表还是第一次用

if (hash.count(key)) 是判断hash表中是否存在关键字key

hash.insert()将字符串插入hash表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值