题目链接:https://www.acwing.com/problem/content/138/
Ⅰ排序+双链表
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
typedef pair<LL, int> PII;
const int N=100010;
int n;
int l[N], r[N], p[N];
PII a[N], ans[N];
int main(){
cin>>n;
for(int i=1; i<=n; i++){
cin>>a[i].first;
a[i].second=i;
}
sort( a+1, a+1+n);
a[0].first=-4e9, a[n+1].first=4e9;
for(int i=1; i<=n; i++){
p[a[i].second]=i;
l[i]=i-1;
r[i]=i+1;
}
for(int i=n; i>1; i--){
int pos=p[i];
LL pv=a[pos].first;
int left=l[pos], right=r[pos];
LL lv=pv-a[left].first, rv=a[right].first-pv;
if(lv<=rv) ans[i]={lv, a[left].second};
else ans[i]={rv, a[right].second};
r[left]=right, l[right]=left;
}
for(int i=2; i<=n; i++) cout<<ans[i].first<<' '<<ans[i].second<<endl;
return 0;
}
Ⅱ 平衡树(map)
ps:这里用java,C++中的高级数据结构用着很奇怪
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int [] w= new int[n];
for(int i=0; i<n; i++) w[i]=sc.nextInt();
TreeMap <Integer, Integer> map=new TreeMap<>();
map.put(w[0], 0);
for(int i=1; i<n; i++){
Map.Entry<Integer, Integer> up=map.ceilingEntry(w[i]);
Map.Entry<Integer, Integer> down=map.floorEntry(w[i]);
int res=Integer.MAX_VALUE, pos=-1;
if(down !=null){
res=w[i]-down.getKey();
pos=down.getValue();
}
if(up !=null && res>up.getKey()-w[i]){
res=up.getKey()-w[i];
pos=up.getValue();
}
System.out.println(res+" "+(pos+1));
map.put(w[i],i);
}
}
}