社区讨论

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

P1678烦恼的高考志愿参与者 10已保存回复 12

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
12 条
当前快照
1 份
快照标识符
@mi6upmq5
此快照首次捕获于
2025/11/20 11:07
4 个月前
此快照最后确认于
2025/11/20 14:39
4 个月前
查看原帖
CPP
// 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;
}

CPP
// 手写
#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;
}

回复

12 条回复,欢迎继续交流。

正在加载回复...