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;
}