题解

简介: AcWing 136. 邻值查找

给定一个长度为 n 的序列 A,A 中的数各不相同。

对于 A 中的每一个数 Ai,求:

min1≤j<i|Ai−Aj|
以及令上式取到最小值的 j(记为 Pi)。若最小值点不唯一,则选择使 Aj 较小的那个。

输入格式
第一行输入整数 n,代表序列长度。

第二行输入 n 个整数A1…An,代表序列的具体数值,数值之间用空格隔开。

输出格式
输出共 n−1 行,每行输出两个整数,数值之间用空格隔开。

分别表示当 i 取 2∼n 时,对应的 min1≤j<i|Ai−Aj| 和 Pi 的值。

数据范围
n≤105,|Ai|≤109
输入样例:
3
1 5 3
输出样例:
4 1
2 1

#include <cstring>
#include <iostream>
#include <algorithm>
#include <set>

using namespace std;
typedef long long LL;
typedef pair<LL, int> PII;

const int N = 100010;

int n;
set<PII> S;

int main()
{
    cin >> n;

    S.insert({2e18, 0});            //哨兵
    S.insert({-2e18, 0});

    for(int i = 1;i <= n;i ++)
    {
        int a;
        cin >> a;

        if(i > 1)
        {
            auto r = S.lower_bound({a, i});
            auto l = r;
            l --;

            LL al = abs(l->first - a);
            LL ar = abs(r->first - a);
            if(al <= ar) cout << al << ' ' << l->second << endl;
            else cout << ar << ' ' << r->second << endl;
        }

        S.insert({a, i});
    }
    return 0;
}
目录
相关文章
|
5月前
Leetcode contests 93 题解
870. Advantage Shuffle 起始就是hdoj 1502田忌赛马,但要求的结果不一样而已。这里我用了个pair来记录B中每个数字对应的位置。
25 0
|
6月前
|
数据安全/隐私保护
[FlareOn6]Overlong 题解
[FlareOn6]Overlong 题解
21 0
|
6月前
|
数据安全/隐私保护
[FlareOn5]FLEGGO 题解
[FlareOn5]FLEGGO 题解
26 1
|
6月前
NSSCTF doublegame题解
NSSCTF doublegame题解
22 0
|
6月前
|
数据安全/隐私保护
[UTCTF2020]babymips 题解
[UTCTF2020]babymips 题解
33 1
|
6月前
|
数据安全/隐私保护
CrackRTF 题解
CrackRTF 题解
19 0
|
Go 数据安全/隐私保护
世上无难事题解
世上无难事题解
59 0
世上无难事题解
|
算法
rsarsa题解
rsarsa题解
108 0
rsarsa题解