邻值查找(平衡树map 或 排序构造双链表 )

在这里插入图片描述
题目链接: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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值