HDU 2838 Cow Sorting 树状数组

Cow Sorting

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 143 Accepted Submission(s): 73
 
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
题目大意:
给出 n 个数,每次可以交换相邻的两个数,代价是: 两个数的和。然后问完全排成升序后,代价是多少。
思路:
反正所有的逆序数都是要交换掉的,不管次序如何,花费的代价是一定的。那么我们只需要求出 当前数之前有多少比它大的,设为 num 个
当前数前面比它大的数总和是多少 设为 sum
花费的代价为:sum+num*当前数的值。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
#define LL long long
#define M 100001
int n;
struct point
{
    int num;
    LL val;
}p[M];
void add(int x,int d)
{
    while(x<=n)
    {
        p[x].num++;
        p[x].val+=d;
        x+=x&-x;
    }
}
int sum_n(int x)//求逆序对
{
    int ret=0;
    while(x)
    {
        ret+=p[x].num;
        x-=x&-x;
    }
    return ret;
}
LL sum_v(int x)
{
    LL ret=0;
    while(x)
    {
        ret+=p[x].val;
        x-=x&-x;
    }
    return ret;
}
int main()
{
    int i,j,k;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<=n;i++)
        {
            p[i].num=p[i].val=0;
        }
        LL final=0,ans;
        for(i=1;i<=n;++i)
        {
            scanf("%d",&k);
            add(k,k);
            ans=i-sum_n(k);
            if(ans)
            {
                LL v=sum_v(n)-sum_v(k);
                final+=(v+k*ans);
            }
        }
        cout<<final<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值