这段代码的目的是找到一个数组中最接近给定值x的k个数。它使用了一个优先队列(堆)来存储最接近x的k个数。
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
struct Compare {
int x;
Compare(int _x) : x(_x) {}
bool operator() (const int& a, const int& b) const {
return abs(a - x) < abs(b - x) || (abs(a - x) == abs(b - x) && a < b);
}
};
int main() {
string line;
getline(cin, line);
istringstream iss(line);
vector<int> arr;
string num;
while (getline(iss, num, ',')) {
arr.push_back(stoi(num));
}
int k, x;
cin >> k >> x;
priority_queue<int, vector<int>, Compare> pq{Compare(x)};
for (int i = 0; i < arr.size(); i++) {
pq.push(arr[i]);
if (pq.size() > k) {
pq.pop();
}
}
vector<int> res;
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
sort(res.begin(), res.end());
for (int i = 0; i < res.size(); i++) {
if (i != 0) {
cout << ",";
}
cout << res[i];
}
cout << endl;
return 0;
}