Skip to content

1010 Lehmer Code

Statement

Metadata

  • 作者: LIU, Yaoting
  • 单位: 浙江大学
  • 代码长度限制: 16 KB
  • 时间限制: 400 ms
  • 内存限制: 64 MB

According to Wikipedia: "In mathematics and in particular in combinatorics, the Lehmer code is a particular way to encode each possible permutation of a sequence of n numbers." To be more specific, for a given permutation of items {A_1, A_2, \cdots, A_n}, Lehmer code is a sequence of numbers {L_1, L_2, \cdots, L_n} such that L_i is the total number of items from A_i to A_n which are less than A_i. For example, given { 24, 35, 12, 1, 56, 23 }, the second Lehmer code L_2 is 3 since from 35 to 23 there are three items, { 12, 1, 23 }, less than the second item, 35.

Input Specification

Each input file contains one test case. For each case, the first line gives a positive integer N (\le 10^5). Then N distinct numbers are given in the next line.

Output Specification

For each test case, output in a line the corresponding Lehmer code. The numbers must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.

Sample Input

6
24 35 12 1 56 23

Sample Output

3 3 1 0 1 0

Solution

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, a[N], b[N];

struct SEG {
    int t[N << 2];
    void init() {
        memset(t, 0, sizeof t);
    }
    void update(int id, int l, int r, int pos, int v) {
        if (l <= pos && r >= pos)
            t[id] += v;
        if (l == r)
            return;
        int mid = (l + r) >> 1;
        if (pos <= mid)
            update(id << 1, l, mid, pos, v);
        else
            update(id << 1 | 1, mid + 1, r, pos, v);
    }
    int query(int id, int l, int r, int ql, int qr) {
        if (ql > qr)
            return 0;
        if (l >= ql && r <= qr)
            return t[id];
        int mid = (l + r) >> 1;
        int res = 0;
        if (ql <= mid)
            res += query(id << 1, l, mid, ql, qr);
        if (qr > mid)
            res += query(id << 1 | 1, mid + 1, r, ql, qr);
        return res;
    }
} seg;

int main() {
    while (scanf("%d", &n) != EOF) {
        for (int i = 1; i <= n; ++i) {
            scanf("%d", a + i);
            b[i] = a[i];
        }
        seg.init();
        sort(b + 1, b + 1 + n);
        for (int i = 1; i <= n; ++i) {
            a[i] = lower_bound(b + 1, b + 1 + n, a[i]) - b;
            seg.update(1, 1, 100000, a[i], 1);
        }
        for (int i = 1; i <= n; ++i) {
            seg.update(1, 1, 100000, a[i], -1);
            printf("%d%c", seg.query(1, 1, 100000, 1, a[i] - 1), " \n"[i == n]);
        }
    }
    return 0;
}

Last update: May 4, 2022
Back to top