【深基17.例5】木材仓库
2024年12月25日小于 1 分钟
set
里面遍历
#include <bits/stdc++.h>
using namespace std;
int n;
set<int> s;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
while (n--)
{
int op, x;
cin >> op >> x;
if (op == 1)
{
if (s.find(x) != s.end())
cout << "Already Exist\n";
else
s.insert(x);
}
else
{
// 暴力枚举
if (s.empty())
{
cout << "Empty\n";
continue;
}
set<int>::iterator ans = s.begin();
for (auto it = s.begin(); it != s.end(); it++)
if (abs(*it - x) < abs(*ans - x))
ans = it;
cout << *ans << "\n";
s.erase(ans);
}
}
return 0;
}
标准做法
#include <bits/stdc++.h>
using namespace std;
int n;
set<int> s;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
while (n--)
{
int op, x;
cin >> op >> x;
if (op == 1)
{
if (s.find(x) != s.end())
cout << "Already Exist\n";
else
s.insert(x);
}
else
{
// 暴力枚举
if (s.empty())
{
cout << "Empty\n";
continue;
}
// 先放到备选答案上
set<int>::iterator ans = s.lower_bound(x);
if (ans == s.end())
ans--;
// 检查前一个位置会不会更好
if (ans == s.begin())
cout << *ans << "\n";
else
{
auto it = ans;
it--;
if (abs(*it - x) <= abs(*ans - x))
ans = it;
cout << *ans << "\n";
}
s.erase(ans);
}
}
return 0;
}