首页 技术 正文
技术 2022年11月14日
0 收藏 398 点赞 2,551 浏览 1985 个字

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

Cow Sorting

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

 #include<stdio.h>
#include<string.h>
#define ll __int64
ll c[+],v[+];
int n;
int Lowbit(int k)
{
return (k&-k);
}
void update(int pos,int num,int val)
{
while(pos<=n)
{
c[pos]+=num;
v[pos]+=val;
pos+=Lowbit(pos);
}
}
ll sum_count(int pos)
{
ll s=; while(pos>)
{
s+=c[pos];
pos-=Lowbit(pos);
}
return s;
}
ll sum(int pos)
{
ll s=; while(pos>)
{
s+=v[pos];
pos-=Lowbit(pos);
}
return s;
}
int main()
{
int i,x;
while(scanf("%d",&n)!=-)
{
memset(c,,sizeof(c));
memset(v,,sizeof(v));
ll ans=,k2,k1;
for(i=;i<=n;i++)
{
scanf("%d",&x);
update(x,,x);
k1=i-sum_count(x);///到此为止 比x大的个数;
/*sum_count[x] 为输入i个数的时候 x之前有sum_count[x]个比x小的数 用i相减则为大于x的个数*/
if(k1!=)
{
k2=sum(n)-sum(x);///到此为止 比x大的数的和;
ans+=x*k1+k2;///到此为止 比x大的数与x交换之后的和;
}
}
printf("%I64d\n",ans);
}
return ;
}

/*坑爹的题    必须用 __int64 不能用long  long  不能用int  ╮(╯▽╰)╭*/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295