hdu 5774 Bubble Sort(树状数组)

该博客分析了如何利用树状数组来解决HDU 5774 Bubble Sort题目。内容指出,对于每个位置i上的数字ai,其能移动的最右边位置是i+fi,其中fi表示ai右侧比它小的数字个数。通过求逆序对的方法可以计算fi,并确定ai的最左边位置为min(ai, i)。" 119040195,5668011,LeetCode每日一题:找重复数,"['算法', 'LeetCode', '数据结构']

分析
对于在位置i的数字ai,假设它右边有fi个比它小的数字,它能被移动的最右边的位置是i+fi
二个这个数字的最左边位置要么是它的起始位置,要么是它排序后的最终位置,所以它的最左边位置就是:min(ai,i)
fi用数组数组求逆序对的方法,求它左边有多少个比它小的数字然后计算出它右边比它小的数字个数即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define pr(x) cout << #x << ": " << x << "  " 
#define pl(x) cout << #x << ": " << x << endl;

struct jibancanyang
{
    int T, n, A[112345];
    int bit[112345];
    int ans[112345];

    int sum(int i) {
        int s = 0;
        while (i > 0) {
            s += bit[i];
            i -= i & -i;
        }
        return s;
    }

    void add(int i , int x) {
        while (i <= n) {
            bit[i] += x;
            i += i & -i;
        }
    }

    void fun() {
        scanf("%d", &T);
        for (int cas = 1; cas <= T; cas++) {
            memset(bit, 0, sizeof(bit));
            scanf("%d", &n);
            for (int i = 1; i <= n; i++) scanf("%d", &A[i]);
            printf("Case #%d:", cas);
            for (int i = 1; i <= n; i++) {
                int x = sum(A[i]);
                int f = A[i] - 1 - x;
                add(A[i], 1);
                ans[A[i]] = i + f - min(A[i], i);
            }
            for (int i = 1; i <= n; i++) 
                printf(" %d", ans[i]);
            puts("");
        }
    }

}ac;

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
#endif
    ac.fun();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值