[Hdu2838] Cow Sorting

描述 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.

输入格式 InputFormat

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.

输出格式 OutputFormat

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

样例输入 SampleInput

3
2
3
1

样例输出 SampleOutput

7


Hdu 2838


代码 Code

树状数组求逆序数。

看了 Discuss 才知道 __int64 才能过。。。。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define ll __int64
const ll maxn=100005;
ll i,j,t,n,m,l,r,k,z,y,x;
ll ans;
struct tnode
{
    ll s,k;
}tree[maxn];
inline ll lowbit(ll s)
{
    return s&(-s);
}
inline void ins(ll s,ll x)
{
    while (s<=n)
    {
        tree[s].s+=x;
        tree[s].k++;
        s+=lowbit(s);
    }
}
inline ll cnt(ll s)
{
    ll t=0;
    while (s>0)
    {
        t+=tree[s].k;
        s-=lowbit(s);
    }
    return t;
}
inline ll sum(ll s)
{
    ll t=0;
    while (s>0)
    {
        t+=tree[s].s;
        s-=lowbit(s);
    }
    return t;
}
int main()
{
    while (~scanf("%I64d",&n))
    {
        ans=0;
        memset(tree,0,sizeof(tree));
        for (i=1;i<=n;i++)
        {
            scanf("%I64d",&x);
            ins(x,x);
            t=i-cnt(x);
            if (t>0) ans+=t*x+sum(n)-sum(x);
        }
        printf("%I64d\n",ans);
        return 0;
    }
}