HDU2838 Cow Sorting (逆序数+求和)

Problem Description
Sherlock's N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock's milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.

Please help Sherlock calculate the minimal time required to reorder the cows.
 

Input
Line 1: A single integer: N
Lines 2..N + 1: Each line contains a single integer: line i + 1 describes the grumpiness of cow i.
 

Output
Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.
 

Sample Input
 
   
3 2 3 1
 

Sample Output
 
   
7
Hint
Input Details Three cows are standing in line with respective grumpiness levels 2, 3, and 1. Output Details 2 3 1 : Initial order. 2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).

         该题求一个序列里面所有逆序对的数字和。对于序列里值为a第i个元素,需要知道前i个元素里比a大的元素的个数以及它们的和,因此需要两个树状数组,一个用来记录数字的个数,另一个记录数字的和,为了简化程序,可以用结构体实现。

#include 
#include 
#include 
using namespace std;

const int maxn = 100001;

int n;

struct cow{
   int cnt;
   __int64 sum;
}tree[maxn];

int Lowbit(int i){
    return i&(-i);
}

void Update(int i,int v,int cnt){
    while(i<=n){
        tree[i].cnt+=cnt;
        tree[i].sum+=v;
        i+=Lowbit(i);
    }
}

__int64 Query_sum(int i){
    __int64 ans=0;
    while(i>0){
        ans+=tree[i].sum;
        i-=Lowbit(i);
    }
    return ans;
}

int Query_cnt(int i){
    int ans=0;
    while(i>0){
        ans+=tree[i].cnt;
        i-=Lowbit(i);
    }
    return ans;
}

int main()
{
    while (scanf("%d", &n)!=EOF)
    {
        __int64 ans = 0;
        memset(tree, 0, sizeof(tree));

        for (int i = 1; i <= n; i++)
        {
            int a;
            scanf("%d", &a);
            Update(a, a, 1);
            __int64 k1 = i - Query_cnt(a);//k1是逆序对数
            if (k1 != 0)
            {
                //所有前n个数的和 – 比a小数的和,即之前比a大的数的总和
                __int64 k2 = Query_sum(n) - Query_sum(a);
                ans += k1 * a + k2;
            }
        }
        printf("%I64d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(线段树&&树状数组)