136. Neighbor value lookup [linked list]

Given a sequence A of length n, the number in A varies. For each number Ai in A, ask:

min1≤j<i|Ai−Aj|
And let the above formula take the minimum j (marked Pi). If the minimum point is not unique, choose the one that makes Aj smaller.

Input format
The first line enters an integer n, representing the length of the sequence.

The second line enters n integers A1... An, which represents the specific values of the sequence, is separated by spaces.

Output format
Output a total of n-1 lines, each line output two integers, the values are separated by spaces.

The corresponding values of min1 < J < i | Ai Aj | and Pi are expressed respectively when i is taken from 2 to n.

Data range
n≤105,|Ai|≤109
Input sample:
3
1 5 3
Output sample:
4 1
2 1

Idea: Sort first, because the number before is considered, so from the last sweep of the sequence, find the two values of An after sorting to compare, save in pair (because positive output), delete this number (using linked list)
Sentinels are set around the list.

#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;
typedef pair<LL, int> PII;// firs store value, second store subscript
const int N = 100010;

int n;
int l[N], r[N];// Left and Right Nodes of L R Inventory List
int p[N];//  Primary array subscripts correspond to linked list positions
PII a[N], ans[N]; //ans save results

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 = -3e9, a[n + 1].first = 3e9; // Sentinel, minimum, Sentry will not affect the number between
    //Array subscripts after sorting links in linked lists
    for (int i = 1; i <= n; i ++ )
    {
        l[i] = i - 1, r[i] = i + 1;
        p[a[i].second] = i;//Primary array subscripts correspond to linked list positions
    }
//Establish a linked list above
    for (int i = n; i > 1; i -- )
    {
        int j = p[i], left = l[j], right = r[j];
        j = The location of the linked list, left,right.
        LL left_value = abs(a[left].first - a[j].first);//Absolute value function abs must be used
        LL right_value = abs(a[right].first - a[j].first);
        if (left_value <= right_value) ans[i] = {left_value, a[left].second};
        else ans[i] = {right_value, a[right].second};
        l[right] = left, r[left] = right;//The last value does not affect the previous value. It should be deleted from the list.
    }

    for (int i = 2; i <= n; i ++ ) cout << ans[i].first << ' ' << ans[i].second << endl;

    return 0;
}

// Establishment of linked list needs: l array, r array, original array subscript corresponding to linked list array subscript

Posted by blkrt10 on Sun, 13 Oct 2019 09:13:22 -0700