zoukankan      html  css  js  c++  java
  • poj2456

    二分法

    有些能用动态规划求解但是超时的题目,可以考虑二分法。

    View Code
    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    #define maxn 100005
    #define inf 0x3f3f3f3f
    
    int n, cow;
    int pos[maxn];
    
    void input()
    {
        scanf("%d%d", &n, &cow);
        for (int i = 0; i < n; i++)
            scanf("%d", &pos[i]);
    }
    
    bool ok(int len)
    {
        int l = 0, r = 0;
        for (int i = 1; i < cow; i++)
        {
            while (r < n && pos[r] - pos[l] < len)
                r++;
            if (r >= n)
                return false;
            l = r;
        }
        return true;
    }
    
    int binary_search()
    {
        int l = inf;
        for (int i = 1; i < n; i++)
            l = min(l, pos[i] - pos[i - 1]);
        int r = (pos[n - 1] - pos[0]) / (cow - 1);
        while (l < r)
        {
            int mid = (l + r) / 2 + ((l + r) & 1);
            if (!ok(mid))
                r = mid - 1;
            else
                l = mid;
        }
        return l;
    }
    
    int main()
    {
        //freopen("t.txt", "r", stdin);
        input();
        sort(pos, pos + n);
        printf("%d\n", binary_search());
        return 0;
    }
  • 相关阅读:
    Netty
    HttpClient 该知道一些概念
    Hibernate QBC 简单收集
    IUAP--单点登录
    js图片压缩和上传并显示
    vue移动端项目
    js自定义滚动条
    mysql5.7以上版本安装
    学习webpack
    学习es6
  • 原文地址:https://www.cnblogs.com/rainydays/p/2577219.html
Copyright © 2011-2022 走看看