Cow Sorting (树状数组)

来源:互联网 发布:小提琴音准训练软件 编辑:程序博客网 时间:2024/05/22 11:06

Cow Sorting

Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 4
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
3231

Sample Output
7
Hint
Input DetailsThree cows are standing in line with respective grumpiness levels 2, 3, and 1.Output Details2 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).

Source
2009 Multi-University Training Contest 3 - Host by WHU


题意:给出n个数,将这n个数按照升序排列,每次排序只可以调换相邻的两个数,则权值为这两个数的和,将

           n个数按照升序排列后,输出所有权值的加和

题解:对于一个数x,设左边有n个数比它大,则这n个数必须移动x右边去,则需要的代价为这n个数的和+x*n,相当于求逆序数。

           ans+=Sum(n,c)-Sum(a[i],c)+(Sum(n,d)-Sum(a[i],d))*a[i];  //Sum(n,c)-Sum(a[i],c)表示a[i]到n即比a[i]的数的和


#include<stdio.h>   #define lowbit(i) (i)&(-i)   __int64 n,a[100005],ans;  __int64 c[100005],d[100005],i;//c保存比x小的数的和,d保存比x小的数的个数    void Add(__int64 i,__int64 val,__int64 c[])  {      for(;i<=100001;i+=lowbit(i)) c[i]+=val;  }  __int64 Sum(__int64 i,__int64 c[])  {      __int64 ret=0;      for(;i>0;i-=lowbit(i)) ret+=c[i];      return ret;  }  int main()  {      scanf("%I64d",&n);      for(i=0;i<n;i++) scanf("%I64d",&a[i]);      for(i=0;i<n;i++)      {          Add(a[i],a[i],c);          Add(a[i],1,d);          ans+=Sum(n,c)-Sum(a[i],c)+(Sum(n,d)-Sum(a[i],d))*a[i];      }      printf("%I64d\n",ans);      return 0;  }  


原创粉丝点击