18731 最接近的值
时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: 不限定
Description
查找特定的值是一种常见的操作,当数据量较大时,往往需要使用高效的结构和查找算法。
n个整数组成的序列,请输出所有元素左侧与它值最为接近的值,我们定义“最接近”为两数之差的绝对值最小。
例如序列 5 1 4 2,1最接近值为5,4最接近值为5,2最接近值为1。
特别的,第一个数的最接近值为它自身。
如果一个数左侧有两个不同的值,绝对值差都是最小。例如3的左边出现了1和5,我们认为值较大的5为最接近值
输入格式
第一行一个整数n。(1<=n<=100000)
第二行n个整数,均为int范围。
输出格式
一行,n个整数,为输入序列对应元素的最接近值。
输入样例
4
5 1 4 2
输出样例
5 5 5 1
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <set>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e5+5;
int n,x;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
multiset<int> s;
int y;
multiset<int>::iterator it;
for(int i=0;i<n;i++)
{
cin >> x;
if(i==0)
y=x;
if(i<=1)
{
printf("%d ",y);
s.insert(x);
continue;
}
it=s.lower_bound(x);
if(it==s.begin())
printf("%d ",*it);
else if(it==s.end())
{
it--;
printf("%d ",*it);
}
else
{
int x1=*it;
it--;
int x2=*it;
if(abs(x1-x)<=abs(x2-x))
printf("%d ",x1);
else
printf("%d ",x2);
}
s.insert(x);
}
printf("\n");
return 0;
}