hdu 2838 Cow Sorting(树状数组)

本文介绍了一道关于重新排列一群奶牛以减少其‘暴躁值’总交换时间的算法问题CowSorting。通过使用树状数组来高效计算逆序对及其累积暴躁值之和,实现了最小化调整所需的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2838点击打开链接

Cow Sorting

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3522    Accepted Submission(s): 1222


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).

题意:树状数组  用两个数组分别储存 逆序的个数 和 比nn大的数的和 因为每次需要两个都移动 因此逆序个数×nn花费固定 加上比nn大的数的和 结果就为所求 

此题long long 过不了 用__int 64

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include<algorithm>
#include <math.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <vector>
using namespace std;
__int64 tree[111111];
__int64 value[111111];
__int64 lowbit(__int64 x)
{
    return x&-x;
}
__int64 getsumtree(__int64 x)
{
    __int64 s=0;
    while(x>0)
    {
        s+=tree[x];
        x-=lowbit(x);
    }
    return s;
}
__int64 getsumvalue(__int64 x)
{
    __int64 s=0;
    while(x>0)
    {
        s+=value[x];
        x-=lowbit(x);
    }
    return s;
}
void add(__int64 x,__int64 num,__int64 val)
{
    while(x<=100000)
    {
        value[x]+=val;
        tree[x]+=num;
        x+=lowbit(x);
    }
}

int main()
{
   __int64 n=0;__int64 sum=0;
   scanf("%d",&n);
   for(__int64 i=1;i<=n;i++)
   {
       __int64 nn=0;
       scanf("%I64d",&nn);
       add(nn,1,nn);
       sum+=(getsumtree(n)-getsumtree(nn))*nn+(getsumvalue(n)-getsumvalue(nn));
   }
   printf("%I64d\n",sum);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值