求助:二分 STL 80 分,手写 100 分

P1678 烦恼的高考志愿

Anguei @ 2018-07-15 09:39:59

// STL
#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    int m, n;
    std::cin >> m >> n;
    std::vector<int> school(m), stu(n);
    for (int i = 0; i < m; ++i)
        std::cin >> school[i];
    for (int i = 0; i < n; ++i)
        std::cin >> stu[i];
    std::sort(school.begin(), school.end());
    int ans = 0;
    for (auto it : stu)
    {
        auto p1 = std::lower_bound(school.begin(), school.end(), it);
        auto p2 = std::lower_bound(school.begin(), school.end(), it) - 1;
        int tmp1 = (p1 != school.end() ? *p1 : 0x7fffffff);
        int tmp2 = (p2 != school.end() - 1 && p2 != school.begin() - 1 ? *p2 : 0x7fffffff);
        tmp1 = abs(tmp1 - it);
        tmp2 = abs(tmp2 - it);
        int tmp = it <= school[0] ? school[0] - it : std::min(tmp1, tmp2);
        ans += tmp;
    }
    std::cout << ans << std::endl;
}
// 手写
#include <vector>
#include <iostream>
#include <algorithm>

int find1(int x, std::vector<int> &school) // 找最小的大于等于 x 的值 
{
    int l = 0, r = school.size() - 1;
    while (l < r)
    {
        int mid = (l + r) >> 1;
        if (school[mid] >= x)
            r = mid;
        else
            l = mid + 1;
    }
    return std::min(abs(school[l] - x), abs(school[l - 1] - x));
}

int main()
{
    int m, n;
    std::cin >> m >> n;
    std::vector<int> school(m), stu(n);
    for (int i = 0; i < m; ++i)
        std::cin >> school[i];
    for (int i = 0; i < n; ++i)
        std::cin >> stu[i];
    std::sort(school.begin(), school.end());
    int ans = 0;
    for (auto it : stu)
        ans += (it <= school.front() ? school.front() - it : find1(it, school));
    std::cout << ans << std::endl;
}

by int_zxc @ 2021-02-04 23:56:54

考古


by 伏地魔老杨 @ 2022-08-13 13:37:07

考古


上一页 |