在一个非降序列中,查找与给定值最接近的元素。
输入 第一行包含一个整数n,为非降序列长度。1 <= n <= 100000。 第二行包含n个整数,为非降序列各元素。所有元素的大小均在0-1,000,000,000之间。 第三行包含一个整数m,为要询问的给定值个数。1 <= m <= 10000。 接下来m行,每行一个整数,为要询问最接近元素的给定值。所有给定值的大小均在0-1,000,000,000之间。 输出 m行,每行一个整数,为最接近相应给定值的元素值,保持输入顺序。若有多个值满足条件,输出最小的一个。 样例输入 3 2 5 8 2 10 5 样例输出 8 5 查看 提交 统计 提问是 using namespace std; #include<iostream> #include<iomanip> #include<stack> #include<fstream> #include<algorithm> #include<vector> #include<iterator> int main() { fstream in("C:\\Users\\admin\\Desktop\\in.txt"); int n,m; int num; vector<int> a; in >> n; for (int i = 1; i <= n; i++) { in >> num; a.push_back(num); } in >> m; sort(a.begin(), a.end()); while (m--) { in >> num; auto p = lower_bound(a.begin(),a.end(),num); int id1; if(p == a.begin()) id1 =* p; else { vector<int>::iterator p1 = --p; p++; if (p == a.end()) id1 =* p1; else { if ((*p - num) >= (num - *p1)) { id1 =* p1; } else id1 =* p; } } cout << id1 << endl;; } } 善用STL,此题和热血格斗场差不多 全局题号 7940 提交次数 72 尝试人数 32 通过人数 28