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 decoqwq @ 2018-07-15 09:56:25
@yyfcpp 氧气了解一下
by Anguei @ 2018-07-15 10:12:27
@刘浩宇(寂) STL 是 WA,不是 TLE
by _ztyqwq @ 2018-07-15 10:25:15
看不懂C++新语法
by partychicken @ 2018-07-15 10:33:26
懵。。。感觉没啥问题啊
by everdream @ 2018-07-15 10:50:20
不知道vector中任何改变容器大小的操作都可能造成以前的迭代器失效吗。。。
by everdream @ 2018-07-15 10:56:56
好吧好像不是这个问题
by everdream @ 2018-07-15 11:22:50
@yyfcpp
int tmp2 = (p2 != school.end() - 1 && p2 != school.begin() - 1 ? *p2 : 0x7fffffff);
这里改成
int tmp2=(p2!=school.begin()-1? *p2:0x7fffffff);
p2可以是最后一个元素
by smallfang @ 2019-05-01 21:39:04
考古
by 0cebeb @ 2019-06-03 09:45:10
考古
by hsaht2426 @ 2020-07-15 16:06:01
考古