在一个非降序列中,查找与给定值最接近的元素。
输入格式:
第一行包含两个数,一个整数n,表示序列中元素个数。(1 ≤ n ≤ 1000000。),一个整数x,表示要查找x的最近邻。
第二行包含n个整数,为非降序列各元素。所有元素的大小均在1~1e9之间。
输出格式:
一个整数,为最接近相应给定值的元素值。若有多个值满足条件,输出最小的一个。
输入样例:
在这里给出一组输入。例如:
3 6
2 5 8
输出样例:
5
这题第一眼看到有序想二分来着,后来贪图简单就瞎搞维护绝对值最小的值了
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1000007)
#define ll long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO {
char print_f[105];
void read() { }
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K, a[MAXN];
int abs(int x) {
return x > 0 ? x : -x;
}
int main() {
#ifdef debug
freopen("test", "r", stdin);
// freopen("out_main", "w", stdout);
clock_t stime = clock();
#endif
read(n, m);
int tabs = INF, key = INF;
for(int i=1; i<=n; i++) { //读入的过程中记录绝对值之差的最小值
read(a[i]);
int j = abs((m - a[i]));
if(j < tabs) {
tabs = j;
key = a[i];
} else if(j == tabs) {
key = min(key, a[i]);
}
}
printf("%d\n", key);
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}