CodeForces:Inversions 2

353 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第22天,点击查看活动详情

题目描述

B - Segment Tree, part 1 - Inversions 2

This problem is the reversed version of the previous one. There was a permutation pi of n elements, for each ii we wrote down the number ai, the number of j such that j<i and pi<pj. Restore the original permutation for the given ai.

Input

The first line contains the number n (1≤n≤10^5), the second line contains n numbers ai. It is guaranteed that ai were obtained from some permutation using the procedure described in the statement.

Output

Print n numbers, the original permutation.

Example

input

5
0 1 1 0 3

output

4 1 3 5 2 

问题解析

这题是说,有这么一个数组a,他有个对应的数组b,b的每一位是a的对应位置上,它的左边有多少个大于他的个数,现在他给你了这个数组b,让你求出数组a。

用线段树来写就是,我们从右往左遍历数组b,准备一个线段树,初始叶子都是1。我们每次在线段树里找从右往左数,找第b[i]个1的位置。之后把那个位置的叶子变成0。

为什么这样可以得到结果?首先,我们是从右往左数第b[i]个1的个数,右边的点都是大于左边的点的。而且因为之前数过的叶子都会变成0,说明变成0的叶子在结果的a数组里应该出现在我们当前找的位置的右边,而我们找的是左边有多少个大于我们的个数。所以就要从右往左找第b[i]个叶子的位置。

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>

#define endl '\n';
typedef long long ll;
typedef pair<int, int> PII;
const int N = 100050;
int f[4 * N], a[N], n;

void buildtree(int k, int l, int r)
{
    if (l == r)
    {
        f[k] = 1;
        return;
    }
    int m = (l + r) / 2;
    buildtree(k + k, l, m);
    buildtree(k + k + 1, m + 1, r);
    f[k] = f[k + k] + f[k + k + 1];
}

void revise(int k, int l, int r, int x)
{
    if (l == r)
    {
        f[k] = 0;
        return;
    }
    int m = (l + r) / 2;
    if (x <= m)revise(k + k, l, m, x);
    else
        revise(k + k + 1, m + 1, r, x);
    f[k] = f[k + k] + f[k + k + 1];
}

int quire(int k, int l, int r, int x)
{
    if (l == r)
    {
        return l;
    }
    int m = (l + r) / 2;
    if (f[k + k + 1] >= x)return quire(k + k + 1, m + 1, r, x);
    else return quire(k + k, l, m, x - f[k + k + 1]);
}

int main()
{
    cin >> n;
    for (int i = n; i >= 1; i--)
    {
        cin >> a[i];
        a[i]++;
    }
    buildtree(1, 1, n);
    vector<int>v(n);
    for (int i = 1; i <= n; i++)
    {
        v[i - 1] = quire(1, 1, n, a[i]);
        revise(1, 1, n, v[i - 1]);
    }
    for (int i = n - 1; i >= 0; i--)cout << v[i] << " ";
    return 0;
}