Reverse Order (tree Edition)

Source: Internet
Author: User

The basic idea is the same as the number of reverse orders for solving a line segment tree. The previous article "reverse order for line segment Tree" also introduced that the input array is discrete first, different elements in the array can be directly hashed. If the same number exists, binary can be used.

After discretization, find f [I] + 1 ~ for each f [I ~ The number in N, that is, to the I position, is a total number larger than F [I]. After statistics, the number at the position of F [I] is increased by 1.

In this way, the statistics are similar to a [I] ~ The sum of N can be imagined to count the tree array in turn, that is, adding lowbit during statistics and downgrading lowbit during update.


Take poj 2299 as an example.

#include <iostream>#include <cstring>#include <cstdio>#include <cmath>#include <set>#include <stack>#include <cctype>#include <algorithm>#define lson o<<1, l, m#define rson o<<1|1, m+1, rusing namespace std;typedef long long LL;const int maxn = 500050;const int mod = 99999997;const int MAX = 0x3f3f3f3f;int n, tmp, f[maxn];LL c[maxn];struct C {    int num, pos;}in[maxn];bool cmp(C x, C y) {    return x.num < y.num;}int main(){    while(cin >> n, n) {        for(int i = 1; i <= n; i++) {            scanf("%d", &in[i].num);            in[i].pos = i;        }        sort(in+1, in+1+n, cmp);        LL sum = 0;        memset(c, 0, sizeof(c));        for(int i = 1; i <= n; i++) f[ in[i].pos ] = i;        for(int i = 1; i <= n; i++) {            for(int j = f[i]+1; j <= n; j += j&(-j))                sum += c[j];            for(int j = f[i]; j > 0; j -= j&(-j))                c[j]++;        }        cout << sum << endl;    }    return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.