- C++
章节11
- @ 2025-4-15 20:30:16
邻值查找
思路:利用STL set寻找绝对值差的最小值即可。
代码:
#include <bits/stdc++.h>
#define PII pair<int,int>
using namespace std;
const int N=1e5+50;
set<PII> s;
int main(){
int a,n;
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> a;
s.insert({a,1});
for(int i=2;i<=n;i++){
cin >> a;
s.insert({a,i});
set<pair<int,int>>::iterator it=s.find({a,i});
pair<int,int> ans={0x3f3f3f3f,0};
if(++it!=s.end()) ans={(*it).first-a,(*it).second};
it--;
if(it--!=s.begin()&&ans.first>=a-(*it).first) ans={a-(*it).first,(*it).second};
cout << ans.first << " " << ans.second << endl;
}
}
0 条评论
目前还没有评论...