hdu 5774 Bubble Sort(树状数组)

来源:互联网 发布:cygwin与linux区别 编辑:程序博客网 时间:2024/05/22 12:14

分析
对于在位置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;}
0 0
原创粉丝点击