前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDUOJ-----2838Cow Sorting(组合树状数组)

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

作者头像
Gxjun
发布2018-03-22 13:04:04
6390
发布2018-03-22 13:04:04
举报
文章被收录于专栏:mlml

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

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

代码:

代码语言:javascript
复制
 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("%I64d\n",res);
44     }
45     return 0;
46 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-04-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Cow Sorting
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档