[SGU 155] Cartesian Tree

Cartesian tree template title, but this question konjac tone tone tone longer than its variant topic, I really was overdone dish

Original title Portal

#include <bits/stdc++.h>
#define ll long long

using namespace std;
const int maxn = 50000 + 10;

int n, top;
int fa[maxn], l[maxn], r[maxn];
int conv[maxn];

struct Node
{
    int id, va, vb;
    bool operator<(const Node &a) const
    {
        return va < a.va;
    }
} a[maxn];

inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch))
        f = (ch == '-') ? -1 : 1, ch = getchar();
    while (isdigit(ch))
        x = x * 10 + (ch - '0'), ch = getchar();
    return x * f;
}

int main()
{
    n = read();
    for (int i = 1; i <= n; i++)
        a[i].va = read(), a[i].vb = read(), a[i].id = i;
    sort(a + 1, a + n + 1);

    conv[a[1].id] = 1;

    stack<int> S;
    S.push(1);
    for (int i = 2; i <= n; ++i)
    {
        conv[a[i].id] = i;
        int fp = 0, sp = 0;
        while (!S.empty())
        {
            int tmp = S.top();
            if (a[tmp].vb < a[i].vb)
            {
                fp = tmp;
                break;
            }
            else
            {
                sp = tmp;
                S.pop();
            }
        }
        fa[i] = fp;
        r[fp] = i;
        l[i] = sp;
        fa[sp] = i;
        S.push(i);
    }

    printf("YES\n");
    for (int i = 1; i <= n; ++i)
    {
        int p = conv[i];
        printf("%d %d %d\n", a[fa[p]].id, a[l[p]].id, a[r[p]].id);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/wyctstf/p/11371570.html