AcWing 136 邻值查找 (set)

https://www.acwing.com/problem/content/138/

找前驱和后继,set基本操作
加哨兵节点

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
#include<set> 
using namespace std;
typedef long long ll;
typedef pair<int, int> P; 

const int maxn = 100010;
const int INF = 1000000007;

int n;

set<P> s;

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read();
	int a;

	set<P>::iterator it1, it2;
	
	s.insert(make_pair(-2e9,0));
	s.insert(make_pair(2e9,0));
	
	a = read();
	s.insert(make_pair(a, 1));

	for(int i=2;i<=n;++i){
		a = read();
		s.insert(make_pair(a,i));
		int mi = INF, p;
		
		it1 = s.lower_bound(make_pair(a,i));
		it2 = s.upper_bound(make_pair(a,i));
		it1--;

		mi = a - it1->first;
		p = it1->second;
		
		if(it2->first - a < mi){
			mi = it2->first - a;
			p = it2->second;
		} 
		printf("%d %d
", mi, p);
	}
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13940128.html