HDUOJ-----2838Cow Sorting(组合树状数组)

时间:2022-05-05
本文章向大家介绍HDUOJ-----2838Cow Sorting(组合树状数组),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Cow Sorting

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

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

Source

2009 Multi-University Training Contest 3 - Host by WHU

求逆序和求和....属于树状数组的组合题目...

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #define maxn 100000
 5 #define lowbit(x) ((x)&(-x))
 6 __int64 aa[maxn+2];  //求逆序数
 7 __int64 bb[maxn+2];  //求和
 8 int n;
 9 void ope(int x,__int64 *dat,int val)
10   {
11       while(x<=n)
12       {
13           dat[x]+=val;
14           x+=lowbit(x);
15       }
16   }
17 __int64 getsum(int x,__int64 *dat)
18 {
19     __int64 ans=0;
20     while(x>0)
21     {
22         ans+=dat[x];
23         x-=lowbit(x);
24     }
25     return ans;
26 }
27 int main()
28 {
29     int i,a;
30     __int64 res;
31    while(scanf("%d",&n)!=EOF)
32     {
33         memset(aa,0,sizeof(aa));
34         memset(bb,0,sizeof(bb));
35         res=0;
36         for(i=0;i<n;i++)
37         {
38             scanf("%d",&a);
39             res+=(getsum(maxn,aa)-getsum(a,aa))*a+(getsum(maxn,bb)-getsum(a,bb));
40             ope(a,bb,a);
41             ope(a,aa,1);  //求逆序数
42         }
43         printf("%I64dn",res);
44     }
45     return 0;
46 }